Passing arrays into functions in C, also known as function parameters, is a common practice enabling functions to operate on data provided by the caller. This method enhances code modularity and flexibility, but it requires understanding of array decaying and function parameters.
In C, arrays decay to pointers when passed into functions. This means the address of the first element is passed, not the array itself. However, accessing array elements from within the function doesn't directly reflect changes in the original array.
Understanding Array Decay
When an array is declared as a function's parameter, it's treated as a pointer to its first element. This 'decaying' behaviour occurs because function parameters in C are predefined as pointers by default.
For instance:
void printArray(int *arr, int n) {
for(int i=0; i
Decay to Pointer
In the above `printArray` function, `arr` is treated as a pointer to the first element. The size `n` is necessary to comprehend the array's complete size.
Calling this function with an array like so:
int arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5);
Will correctly print array elements.
Array Changes Inside Function
Despite the fact that the array decays to a pointer, modifications within the function don't reflect back to the original array:
void modifyArray(int *arr, int n) {
arr[0] = 10;
}
If you call this function with `arr[5]` and then print `arr`, it will still display the original first element, not the changed one.
Passing Arrays by Reference
To make changes within a function reflect back to the original array, one must use pointers or dynamically allocated arrays.
We can create an array with `malloc`, or use advanced features like arrays of pointers or multi-dimensional arrays to pass arrays by reference:
Using malloc
Allocate memory dynamically, modify, and then free it:
int *arr = malloc(5 * sizeof(int)); modifyArr(&arr, 5); free(arr);
Arrays of Pointers
Treating arrays like arrays of pointers and changing the structure within the function:
void modifyArray(int **arr, int n) {
arr[0] = 10;
}
In conclusion, understanding how arrays decay to pointers and behave within functions is vital for C programming. With careful implementation, you can retain the benefits of passing arrays while mitigating potential complexities and pitfalls.








![Print reverse of array| passing array into function using pointer [Part 04]](https://i.pinimg.com/originals/2b/97/9b/2b979b0fe01cd4d9571475e8ef8f9e65.jpg)




