In C, what does the expression sizeof(a) / sizeof(a[0]) evaluate to when a is declared as int a[5]; on a machine where int is 4 bytes?
Correct answer
B. 5, the number of elements in the array
14 views
B. 5, the number of elements in the array
14 views
The sizeof operator reports the storage size of its operand in bytes, so sizeof(a) is 20 and sizeof(a[0]) is 4, and dividing them gives the element count 5. This is the standard C idiom for finding array length without a separate variable. It works only while a is still an array: once the array decays to a pointer in a function parameter, sizeof(a) becomes the pointer size, so the idiom silently breaks there.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is B? Ask here and get an explanation.