Data Structures & AlgorithmsHardTCS NQT · Infosys pattern

What is printed? (C: array passed to a function decays to a pointer)

What is printed? (C: array passed to a function decays to a pointer)
void f(int a[]) { printf("%zu ", sizeof(a) / sizeof(a[0])); }
int main(void) {
    int a[10];
    printf("%zu ", sizeof(a) / sizeof(a[0]));
    f(a);
    return 0;
}   /* 64-bit system: 8-byte pointers, 4-byte int */
  1. A. 10 10
  2. B. 10 1
  3. C. 40 8
  4. D. 10 2

Correct answer: D. 10 2

In main, a is an array of 10 ints: 40 / 4 = 10. A parameter declared int a[] is really int *a, so inside f sizeof(a) is the pointer size 8, giving 8 / 4 = 2. Pass the length separately – the classic array-length bug.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic