The size of an array can be calculated using the sizeof operator. It returns the total size of the array in bytes, including the storage occupied by all its elements.
#include <stdio.h>
int main(void)
{
int numbers[] = {10, 20, 30, 40, 50};
size_t total_size = sizeof(numbers);
size_t element_size = sizeof(numbers[0]);
size_t element_count = total_size / element_size;
printf("Array size: %zu bytes\n", total_size);
printf("Element size: %zu bytes\n", element_size);
printf("Number of elements: %zu\n", element_count);
return 0;
}
Example Output #
On an implementation where sizeof(int) is 4 bytes:
Array size: 20 bytes
Element size: 4 bytes
Number of elements: 5
Explanation #
The expression:
sizeof(numbers)
returns the total size of the array in bytes.
The expression:
sizeof(numbers[0])
returns the size of one array element.
Dividing the total array size by the size of one element calculates the number of elements:
sizeof(numbers) / sizeof(numbers[0])
This calculation works when numbers is an actual array object, rather than a pointer to an element.
Array Size Expressions #
| Expression | Purpose |
|---|---|
sizeof(numbers) |
Total array size in bytes |
sizeof(numbers[0]) |
Size of one element in bytes |
sizeof(numbers) / sizeof(numbers[0]) |
Number of elements in the array |
The sizeof operator returns a value of type size_t, which should be printed using %zu.
Important: When an array is passed to a function as a parameter, it is adjusted to a pointer parameter. Inside that function, sizeof returns the size of the pointer, not the size of the original array. The array length must be passed separately when needed.