Count Array Slots Safely
Count the bins before indexing
Five bins need five positions, but their last index is 4:
Index 5 is outside this array, and C will not check for you. To find the count without repeating the number 5, divide the size of the whole local array by the size of one element. sizeof screws counts bytes in the whole array, while sizeof screws[0] counts bytes in one element. Their quotient counts elements without assuming an int has a particular byte size.
The result has type size_t, an unsigned integer type used for sizes and counts; printf displays it with %zu. An empty [] in this initialized declaration lets C count the five initial values for you.
#include <stdio.h>
int main(void) {
int screws[] = {2, 4, 6, 8, 10};
size_t count = sizeof screws / sizeof screws[0];
printf("Bins: %zu\n", count);
printf("Last bin: %d\n", screws[count - 1]);
return 0;
}
count - 1 is the last valid index here because the array is nonempty. If the last two initial values were removed, the count would be 3 and the last value would be 6. Trace that variation on paper rather than changing this read-only example. This calculation works while screws is an array in the current scope. A function receiving it as a parameter needs the count passed separately.