The Size of an Array

A constant like COUNT has one weakness: you have to keep it in line with the array yourself. When you add an element to the array and forget the constant, the loop skips the new element. When you remove one, the loop goes past the end. C can work out the number of elements from the array itself, with sizeof.

sizeof (size of) tells you how much memory something takes up, in bytes. A byte is the smallest unit of memory. Here, one int takes up 4 bytes, so an array of five ints takes up 20 bytes. If you divide the size of the whole array by the size of one element, you get the number of elements:

int scores[] = {80, 92, 75, 60, 88};
int count = sizeof(scores) / sizeof(scores[0]);
printf("%d\n", count);

This prints:

5

sizeof(scores) is 20, the size of the whole array. sizeof(scores[0]) is 4, the size of the first element. All elements have the same type, and so the same size, which makes 20 / 4 = 5 exactly the number of elements. It works for arrays of any type: a double takes up 8 bytes, but the division again gives the number of elements.

Now the loop always fits the array. Add a value to the array, and count changes by itself:

int scores[] = {80, 92, 75, 60, 88, 95};
int count = sizeof(scores) / sizeof(scores[0]);
for (int i = 0; i < count; i++) {
    printf("%d ", scores[i]);
}
printf("\n");

This prints:

80 92 75 60 88 95

Two mistakes are common here:

  • Forgetting the division. sizeof(scores) alone is 20, the number of bytes, not elements. A loop up to 20 goes past the end and stops with RuntimeError: unreachable.
  • Printing sizeof straight away with %d. sizeof gives a different type of whole number than int, so printf("%d\n", sizeof(scores) / sizeof(scores[0])); doesn't compile: error: format specifies type 'int' but the argument has type '__size_t' (aka 'unsigned long'). Store the result in an int variable first, as in the examples above.

Instructions

Create a variable count of type int with the number of elements of prices. Calculate it with sizeof, don't write 4.

Write a for loop that goes through the indexes while they're less than count, and prints each price on its own line with two decimal places (%.2f): 29.90, 149.00, 99.50 and 15.00.

A new product has arrived in the shop. Add a fifth price, 5.49, at the end of the array, inside the curly braces. Don't change anything else, and run the program: the loop prints the new price too, because count is now 5.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/12