C Programming Basics
void f(int a[10]) {
printf("%zu\n", sizeof a);
}
int main(void) {
int b[10] = {0};
printf("%zu ", sizeof b);
f(b);
return 0;
}int is 4 bytes and pointers are 8 bytes. Which of the following is the output when the program above is executed?
- A10 10
- B40 8
- C40 40
Show answer and explanation
Answer: B. 40 8
b in main is an int array of 10 elements, so sizeof b is 10 × 4 = 40 bytes. Even when a function parameter is written as int a[10], the parameter is treated not as an array but as a pointer to int (int *a), and f(b) passes only the address of the first element. So sizeof a inside f is 8, the size of a pointer. gcc's -Wall gives a warning for this sizeof. When a function needs the number of elements of an array, it is passed as a separate argument.
- A. sizeof returns a number of bytes, not a number of elements.
- B. Correct. It is 40 bytes for the whole array in main and 8 bytes for the pointer in f.
- C. The parameter a is a pointer, not an array, so it does not give 40 inside f.