Lesson 32: Passing Arrays to Functions
When an array name is passed to a function, C effectively uses Call by Reference (or, more accurately, Call by Pointer).
What is Passed?
When you pass an array name (e.g., my_array), C treats it as a pointer to its first element. The function receives the memory address of the array's start.
Because the function receives the address, any changes made to the array elements inside the function will affect the original array outside.
Function Definition Syntax
When declaring the parameter, you must specify the type, but the size is optional (and usually omitted).
c // All three prototypes below are equivalent when used as parameters: void print_array(int arr[], int size); void print_array(int arr[10], int size); // Size is ignored by the compiler void print_array(int *arr, int size); // The clearest way to show it's a pointer
Example: Modifying an Array
c #include <stdio.h>
void double_elements(int arr[], int n) { for (int i = 0; i < n; i++) { arr[i] *= 2; // Original array is modified } }
int main() { int data[3] = {1, 2, 3};
// Passing array name (address) and size
double_elements(data, 3);
printf("New data: %d, %d, %d\n", data[0], data[1], data[2]);
// Output: 2, 4, 6
return 0;
}
Crucial Point: Since the function loses knowledge of the array's size when it receives the pointer, you must almost always pass the size as a separate integer argument.