Experiment: inside a function sizeof(a) gives pointer size
Rule: always pass the length as another argument
Defer 2D arrays; master 1D first
π‘ Tip: In void f(int a[], int n), int a[] is just another spelling of int *a. The callee cannot see the total array size.
Passing an Array to a Function
Passing an array to a function uses a slightly special parameter syntax.
// Two equivalent parameter formsintsumArray(int a[], int n) { ... }
intsumArray(int *a, int n) { ... }
intmain(void) {
int scores[5] = {80,65,92,78,88};
int total = sumArray(scores, 5); // pass the array name alone (no &)printf("%d\n", total);
}
intsumArray(int a[], int n) {
int s = 0;
for(int i=0; i<n; i++) s += a[i];
return s;
}
Array size: The function has no way to know the array size on its own, so the standard convention is to pass the size as another argument.
Pass-by-Value vs Pass-by-Reference
Plain int/double are passed as a copy of the value, but arrays are passed as the address of the first element.
Regular pass-by-value (int, double)
Modifying the parameter inside the function does not affect the caller (only the copy is changed).
Passing an array
Because the address is passed, writing a[i] = 0 inside the function also changes the caller's array!
voidreset(int a[], int n) {
for(int i=0; i<n; i++) a[i] = 0; // the caller's array becomes 0 too
}
intmain(void) {
int x[3] = {1,2,3};
reset(x, 3);
printf("%d %d %d\n", x[0], x[1], x[2]); // β 0 0 0
}
The sizeof Pitfall
You cannot use sizeof(a) inside the function! Inside the function, the array parameter is actually a pointer, so sizeof returns only the size of a pointer (for example 8 bytes).
intmain(void) {
int a[5];
printf("%ld\n", sizeof(a)); // 20 (5 elements Γ 4 bytes)test(a);
}
voidtest(int a[]) {
printf("%ld\n", sizeof(a)); // 8 (size of a pointer)!
}
Workaround: Always pass the size as a separate argument, or share it as a constant via a macro / #define.
Try It Yourself β Array as Argument
arr_param.c
Output
Click Run...
π‘ Try these ideas too
Function that fills an array with 0
Function that returns the sum given an array and its size
Confirm the caller sees the changes done inside the callee
Function taking a 2D array (column count in the type)