Arrays
Prerequisites: Loops
An array is a fixed-size, contiguous block of memory holding values
of the same type, indexed from 0.
int scores[3] = {90, 85, 77};
printf("%d\n", scores[0]); // 90
scores[1] = 88;
for (int i = 0; i < 3; i++) {
printf("%d\n", scores[i]);
}
Crucially, C performs no bounds checking at all — reading or
writing scores[10] on a 3-element array doesn't raise an error the
way it would in Java or Python; it silently reads or corrupts
whatever memory happens to be there, which is a common source of
hard-to-find bugs (and security vulnerabilities).
Since there's no .length, the size must be tracked separately —
sizeof(scores) / sizeof(scores[0]) gives the element count for a
real array (not one passed into a function, where this trick breaks
down — covered in Pointers & Arrays, in Level 2).
Common mistakes
- Assuming an out-of-bounds access will crash immediately and obviously — it often doesn't, which is what makes this class of bug dangerous rather than merely annoying.
Practice
Declare an int array of 5 numbers, and print their sum using a
for loop.
Show solution
int nums[5] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += nums[i];
}
printf("%d\n", sum); // 15