Arrays and Zero-Based Indexes
Keep three readings together
Suppose you need to keep three temperature readings. An array gives those readings one name and numbered positions called indexes. In int temps[3] = {18, 20, 22};, the bracketed 3 reserves three int elements; the braces supply their initial values in order. The elements are contiguous: each follows the previous one without gaps between elements.
Indexes start at zero, so temps[0] is 18 and temps[2] is 22. There is no temps[3] element. Reading or writing there has undefined behavior: C promises no particular result, not even a helpful error. Do not test an invalid index by running it.
A loop can visit the elements by index. Here temps[i] selects the current reading and total += temps[i] adds it to the running total. The condition i < 3 stops before the invalid index 3.
#include <stdio.h>
int main(void) {
int temps[3] = {18, 20, 22};
int total = 0;
for (int i = 0; i < 3; i++) {
total += temps[i];
}
printf("Total: %d\n", total);
return 0;
}
On each pass, i names a valid slot: 0, 1, or 2.
An element can be changed using its index:
#include <stdio.h>
int main(void) {
int marks[2] = {5, 6};
marks[1] = 8;
printf("Second mark: %d\n", marks[1]);
return 0;
}
Only the second element changes. The first still holds 5.
Storage and bounds
The declared array has a fixed number of elements; assigning a new value to one element does not resize it. You must keep each index within that count. The next demo introduces sizeof, which can measure a whole array where it is declared. Later, pointers will explain why passing an array to a function needs a separate count.