Array length computation in C: For the array below, what does sizeof(arr)/sizeof(arr[0]) evaluate to?\n#include<stdio.h>\n\nint main()\n{\n float arr[] = {12.4, 2.3, 4.5, 6.7};\n printf("%d\n", sizeof(arr) / sizeof(arr[0]));\n return 0;\n}

Difficulty: Easy

Correct Answer: 4

Explanation:


Introduction / Context:
Counting elements in a statically allocated array is a common pattern in C. The idiom sizeof(arr)/sizeof(arr[0]) calculates the number of elements at compile time.



Given Data / Assumptions:

  • arr is a complete object array with four float elements.
  • sizeof(arr) yields total bytes in the array.
  • sizeof(arr[0]) yields bytes per element (here, size of float).


Concept / Approach:
The quotient sizeof(arr)/sizeof(arr[0]) equals the element count when used on the array in the same scope (not after decay to pointer). Since there are exactly four initializers, arr has length 4, so the expression yields 4 regardless of platform (assuming no VLAs here).



Step-by-Step Solution:
Compute total size: sizeof(arr) = 4 * sizeof(float).Compute element size: sizeof(arr[0]) = sizeof(float).Divide → 4.



Verification / Alternative check:
Add a static assert or print with %zu to confirm; altering the initializer count adjusts the quotient accordingly.



Why Other Options Are Wrong:
They guess or assume padding/alignment affects the quotient; alignment does not change the element count formula.



Common Pitfalls:
Applying the idiom after arr decays to float* (e.g., in function parameters), which returns the wrong value; confusing number of bytes with number of elements.



Final Answer:
4

More Questions from Arrays

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion