Example 1 — Array length with sizeof
The element count is total bytes divided by element size.
#include <stdio.h>
int main(void) {
int scores[10] = {0};
char name[] = "C";
printf("sizeof(int) = %zu\n", sizeof(int));
printf("sizeof scores = %zu\n", sizeof scores);
printf("length = %zu\n", sizeof scores / sizeof scores[0]);
printf("sizeof name = %zu\n", sizeof name);
return 0;
} How It Works
- The array holds 10 ints of 4 bytes each = 40 bytes.
- Dividing by
sizeof scores[0]gives the element count, 10. "C"needs 2 bytes:'C'and the terminating'\0'.- Sizes assume a typical platform where
intis 4 bytes.
