Try it yourself: inside a function sizeof(a) gives the pointer size
Rule of thumb: always pass the length as a separate argument
Skip 2D arrays for now β master 1D first
π‘ Tip: in void f(int a[], int n), int a[] is just another way to spell int *a. The callee can't see the original array size.
Passing an Array to a Function
Passing an array to a function uses a slightly unusual 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 how many elements were passed, so the standard convention is to pass the size as an extra argument.
Passing Values vs Passing Array Addresses
Plain types like int and 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)
Changes to the parameter inside the function don't affect the caller β only the copy is modified.
Passing an array
Since the address is what's passed, 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
Don't use sizeof(a) inside the function! Inside the function, the array parameter is really a pointer, so sizeof just gives you the size of a pointer (typically 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
Press Runβ¦
π‘ Try these ideas too
Write a function that fills an array with zeros
Write a function that returns the sum given an array and its size
Verify the caller sees the changes the callee made
Write a function that takes a 2D array (with the column count in the type)