$ overview
overview/0x07·Functions & Data

Arrays

Contiguous blocks of the same type, indexing, and iterating over them.

An array is a fixed-size, contiguous block of memory holding values of the same type. "Contiguous" is the key word — it's what makes indexing fast, and it's the property pointers will later exploit directly.

Declaring and initializing

arrays.c
1int scores[5]; // 5 uninitialized ints
2int primes[5] = {2, 3, 5, 7, 11}; // explicit values
3int zeros[5] = {0}; // first element 0, rest zero-filled
4int inferred[] = {1, 2, 3}; // size inferred: 3

Indexing

Elements are accessed with square brackets, and indexing starts at 0. The last valid index is always length - 1:

indexing.c
1int primes[] = {2, 3, 5, 7, 11};
2 
3printf("%d\n", primes[0]); // 2, the first element
4printf("%d\n", primes[4]); // 11, the last element
5 
6primes[2] = 6; // overwrite an element
error: C does not check array bounds
primes[5] or primes[-1] compiles without complaint. At runtime it reads or writes whatever memory happens to sit there — sometimes it crashes immediately, sometimes it silently corrupts an unrelated variable, and sometimes it appears to work until it doesn't. Keeping indices inside [0, length) is entirely your responsibility.

Iterating over an array

sum.c
1int nums[] = {4, 8, 15, 16, 23, 42};
2int length = sizeof(nums) / sizeof(nums[0]);
3int sum = 0;
4 
5for (int i = 0; i < length; i++) {
6 sum += nums[i];
7}
8printf("Sum: %d\n", sum);

sizeof(nums) / sizeof(nums[0]) is the standard way to get an array's length: total bytes divided by the size of one element. It only works on the original array variable, not on a pointer to it — a distinction that becomes important in 0x0A.

Multidimensional arrays

An array of arrays models a grid. Rows are still contiguous in memory, laid out one after another:

grid.c
1int grid[2][3] = {
2 {1, 2, 3},
3 {4, 5, 6}
4};
5 
6for (int row = 0; row < 2; row++) {
7 for (int col = 0; col < 3; col++) {
8 printf("%d ", grid[row][col]);
9 }
10}
11// prints: 1 2 3 4 5 6
note: Arrays passed to functions decay to pointers
When you pass an array as a function argument, the function actually receives a pointer to its first element — it has no way to know the original length. That's why array-processing functions almost always take a length parameter alongside the array itself, as in the sum example above.