How to pass arrays to C functions, and how they relate to pointers.
sizeof in the callee gives pointer size, not array sizeint a[n] (C99)const to mark read-onlysizeof(a) gives the pointer sizevoid f(int a[], int n), int a[] is just another way to spell int *a. The callee can't see the original array size.
// Two equivalent parameter forms int sumArray(int a[], int n) { ... } int sumArray(int *a, int n) { ... } int main(void) { int scores[5] = {80,65,92,78,88}; int total = sumArray(scores, 5); // pass the array name alone (no &) printf("%d\n", total); } int sumArray(int a[], int n) { int s = 0; for(int i=0; i<n; i++) s += a[i]; return s; }
int and double are passed as a copy of the value, but arrays are passed as the address of the first element.a[i] = 0 inside the function also changes the caller's array!void reset(int a[], int n) { for(int i=0; i<n; i++) a[i] = 0; // the caller's array becomes 0 too } int main(void) { int x[3] = {1,2,3}; reset(x, 3); printf("%d %d %d\n", x[0], x[1], x[2]); // β 0 0 0 }
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).int main(void) { int a[5]; printf("%ld\n", sizeof(a)); // 20 (5 elements Γ 4 bytes) test(a); } void test(int a[]) { printf("%ld\n", sizeof(a)); // 8 (size of a pointer)! }
#define.Check your understanding of this lesson.
In C, the array name decays to a pointer to its first element, so the function actually receives an address.
Because the function works through a pointer, writing to the elements mutates the caller's array as well.
Only a pointer makes it into the function, so sizeof can't recover the original length β pass the count as a separate argument.