Nearby lessons
56 of 124C - Array Size
How to find the size of an array in C with the sizeof(arr) / sizeof(arr[0]) idiom — and the critical reason it stops working once the array is passed to a function.
sizeof Gives Bytes, Not Elements
sizeof reports how many bytes something occupies. For an array that is the element count multiplied by the size of one element:
The Standard Idiom
Divide the total size by the size of one element and the units cancel, leaving the count:
Why Divide by arr[0] and Not sizeof(int)?
Both give the right answer today. Only one keeps working when you change the array's type tomorrow:
A Reusable Macro
Because the idiom is used so often, most C projects define a macro for it:
The Trap — sizeof Inside a Function
This is the single most important thing to know about array size in C. When an array is passed to a function, it decays into a pointer, and the size information is lost:
Why the Function Sees 8 Bytes
sizeof(arr) reports 8. Dividing 8 by 4 gives 2, which has nothing to do with the real length.The parameter forms int arr[], int arr[5] and int *arr are all treated identically by the compiler. Even writing the size in the brackets does not preserve it.
The Fix — Pass the Size
Compute the size in the scope where the array was declared, then hand it over as a parameter:
Common Mistakes
| Mistake | Result |
|---|---|
Using sizeof(arr) as the count | Loops 20 times over a 5-element array |
Calling sizeof on a parameter | Gives the pointer size, not the array size |
Dividing by sizeof(int) | Breaks silently when the type changes |
Using strlen on a number array | strlen is for strings only |
Trusting int arr[5] as a parameter | The 5 is ignored by the compiler |
memcpy(dst, src, n), fgets(buf, n, stdin), qsort(base, n, size, cmp). The language cannot tell them, so you must.- sizeof(arr) gives the total bytes, not the element count.
- Element count = sizeof(arr) / sizeof(arr[0]).
- Divide by arr[0], not by sizeof(int), so it survives a type change.
- Inside a function the array decays to a pointer and sizeof gives the pointer size.
- Always pass the size as a second parameter.