To get the size of an array, you can use the sizeof
operator:
int myNumbers[] = {10, 25, 50, 75, 100}; printf(“%lu”, sizeof(myNumbers)); // Prints 20 |
Why did the outcome display 20 instead of 5, despite the array comprising 5 elements? |
This occurs because the sizeof operator provides the size of a type in bytes.
As covered in the Data Types chapter, an int type typically occupies 4 bytes. Thus, in the example above, 4 x 5 (4 bytes x 5 elements) equals 20 bytes.
Understanding the memory size of an array is beneficial for larger programs that demand effective memory management.
However, if you simply aim to determine the number of elements within an array, you can employ the following formula, which divides the size of the array by the size of one array element:
int myNumbers[] = {10, 25, 50, 75, 100}; int length = sizeof(myNumbers) / sizeof(myNumbers[0]); printf(“%d”, length); // Prints 5 |
In the array loops section in the previous chapter, we specified the size of the array in the loop condition (i < 4). However, this approach is not ideal as it will only function correctly for arrays of a specific size.
By employing the sizeof formula from the example above, we can now create loops that accommodate arrays of any size, ensuring greater versatility and sustainability.
Instead of specifying:
int myNumbers[] = {25, 50, 75, 100}; int i; for (i = 0; i < 4; i++) { |
It’s preferable to express:
int myNumbers[] = {25, 50, 75, 100}; int length = sizeof(myNumbers) / sizeof(myNumbers[0]); int i; for (i = 0; i < length; i++) { |