How to pass arrays to C functions, and how they relate to pointers.
// 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; }
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 actually a pointer, so sizeof returns only the size of a pointer (for example 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)! }
Check your understanding of this lesson.
In C, the array name decays to a pointer to its first element, so the address is what the function receives.
Because the function works through a pointer, writing to the elements mutates the caller's array too.
Only a pointer reaches the function, so sizeof cannot recover the original length β pass the count as another argument.