C Array Size
Sometimes you need to know how many elements an array actually has, especially when looping through it. Writing the size as a fixed number works, but it is easy to get wrong if the array changes later. C gives you the sizeof operator so you can let the compiler calculate the size for you.
The sizeof Operator
The sizeof operator tells you how many bytes something takes up in memory. When you apply it to an entire array, you get the total number of bytes used by all of its elements combined.
Total bytes of an array
#include <stdio.h>
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
printf("Total bytes: %lu\n", sizeof(myNumbers));
return 0;
}On most systems an int takes up 4 bytes, so an array of 5 integers uses 20 bytes. That total is useful, but usually you want the count of elements, not the byte count.
Getting the Number of Elements
To find how many elements an array holds, divide the total size of the array by the size of a single element. Because every element is the same type, this always gives you the correct count.
Calculating the element count
#include <stdio.h>
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
printf("The array has %d elements\n", length);
return 0;
}Using the Size in a Loop
The real benefit shows up in loops. Instead of hard-coding the limit, use the calculated length as the loop's stopping condition. Now the loop always matches the array, even if its size changes.
Looping with a calculated length
#include <stdio.h>
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
for (int i = 0; i < length; i++) {
printf("%d\n", myNumbers[i]);
}
return 0;
}Typical sizes on a common system