Loading lessons...
Finding the Array Size
Finding the Array Size
You don't need to count elements by hand: sizeof can tell you the array length.
The trick
Divide the total bytes by the bytes of one element:
int myNumbers[] = {10, 25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
printf("%d", length); // 5
sizeof(myNumbers)= bytes of the whole array.sizeof(myNumbers[0])= bytes of one int.- Divide them to get the element count.
Loop with the computed size
for (int i = 0; i < length; i++) {
printf("%d\n", myNumbers[i]);
}
No hard-coded counting, easy to change the array.
When it doesn't work
The trick works only on the array itself inside its own scope. Passed to a function as a parameter, the array "decays" to a pointer, so sizeof no longer gives the full size.
TL;DR
- size =
sizeof(arr) / sizeof(arr[0]). - Loop with the computed length instead of hard-coding.
- Update the array and the loop adapts.
- Lost size is a pointer thing - more on functions later.