Lesson 15 / 36

Arrays

A fixed-size sequence of same-typed values, in 1D and beyond.

One name, many slots

An array stores a fixed number of values of the same type under one name, indexed from 0. int scores[5]; reserves room for 5 ints.

Declare, initialise, index

Indexes run from 0 to length - 1. Reading past the end is undefined behavior, not a safe error.

int nums[5] = {10, 20, 30, 40, 50};
printf("%d\n", nums[0]);   // 10
printf("%d\n", nums[4]);   // 50

for (int i = 0; i < 5; i++) {
    printf("%d ", nums[i]);
}

Output:

10
50
10 20 30 40 50

Multi-dimensional arrays

A 2D array is an array of arrays — think of it as a grid with rows and columns.

int grid[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};
printf("%d\n", grid[1][2]); // row 1, col 2

Output:

6

sizeof reveals total bytes

sizeof(nums) gives the array's total bytes, not element count. Use sizeof(nums) / sizeof(nums[0]) for element count.