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?

  1. A10 10
  2. B40 8
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. int is 4 bytes. Which of the following is the output when the code above is executed?
  2. Which of the following is the output when the code above, which concerns a char array holding a string, is executed?
  3. After the declarations above, one of the statements A "p = t;", B "*p = 'x';", C "q = t;" or D "*q = 'x';" is written. Which of the following is the combination that causes compile errors?
  4. Which of the following is the output when the program above, which uses an array of function pointers, is executed?
  5. fill and use are functions defined elsewhere. Which of the following is a problem with the function above?