Arrays in memory
A C array is a row of same-sized values packed side by side in memory. Indexes start at 0, and nothing stops you walking off the end.
A row of boxes
int scores[5] = {12, 7, 30, 18, 4}; asks for room for five ints, side by side. Each int is 4 bytes, so the five values take 20 bytes in one unbroken block. The size is fixed when you declare it: an array cannot grow.
scores[i] means "start at the beginning, skip i ints, read the one there". That is why the first value is scores[0]: it is zero steps from the start.
Indexes and the end
Five values means indexes 0 to 4. Index 5 is the first address past the end: no box there belongs to scores.
scores holds 12, 7, 30, 18, 4.
C does not check. scores[5] compiles and runs, and reads whatever happens to sit next in memory, maybe another variable. Writing there quietly changes that other thing. Far past the end, you hit memory the program does not own, and this site stops with memory access out of bounds. The rule: a loop over n items runs i = 0 while i < n, never i <= n.
C arrays also do not know their own length. Inside the function that declares one, sizeof scores / sizeof scores[0] gives 5. Once you pass it to another function you only have the address of the first item, so you pass the length too.
Run it: a high-score table
Run it, then change one thing and run it again.
#include <stdio.h>
int main(void) {
int scores[5] = {12, 7, 30, 18, 4};
int n = sizeof scores / sizeof scores[0];
int best = scores[0];
for (int i = 0; i < n; i++) {
printf("scores[%d] = %d\n", i, scores[i]);
if (scores[i] > best) {
best = scores[i];
}
}
printf("%d scores, %d bytes, best %d\n", n, (int)sizeof scores, best);
return 0;
}
A total with an extra round
total should add up the four lap times, 58 + 61 + 57 + 60 = 236. It prints something else, because the loop reads one box too many. Fix the loop.
#include <stdio.h>
struct race {
int laps[4];
int penalty;
};
int main(void) {
struct race r = {{58, 61, 57, 60}, 15};
int total = 0;
for (int i = 0; i <= 4; i++) {
total += r.laps[i];
}
printf("total %d\n", total);
return 0;
}