Lesson content
Read, practise, then check your understanding
An array is a fixed-size sequence of elements of one type stored contiguously. This layout enables constant-time indexed access and predictable traversal, but C performs no automatic bounds checking.
One-dimensional arrays
int scores[5] = {72, 88, 91, 64, 85};
int zeroed[10] = {0};
size_t count = sizeof scores / sizeof scores[0];
Valid indexes are 0 through count - 1. Reading or writing outside the array is undefined behavior. When an initializer supplies fewer values, remaining elements are zero-initialized.
Passing arrays to functions
In a parameter, int values[] and int *values describe the same adjusted pointer type. The function cannot recover the original count with sizeof.
int maximum(const int *values, size_t count, int *result) {
if (values == NULL || result == NULL || count == 0) return 0;
int max = values[0];
for (size_t i = 1; i < count; ++i)
if (values[i] > max) max = values[i];
*result = max;
return 1;
}
The pointer-plus-length convention is fundamental to C APIs.
Two-dimensional arrays
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printf("%d\n", matrix[1][2]); // 6
C uses row-major order. When passing a true 2D array, every dimension except the first must be known so the compiler can calculate each row address:
void clear(size_t rows, size_t cols, int matrix[rows][cols]) {
for (size_t r = 0; r < rows; ++r)
for (size_t c = 0; c < cols; ++c)
matrix[r][c] = 0;
}
This C99 syntax uses variable-length array parameters. Projects avoiding VLAs can pass a fixed column count or flatten the data and calculate row * columns + column.
Multidimensional and dynamic choices
Higher dimensions follow the same row-major nesting. Large automatic arrays risk exhausting stack space. An array of pointers is not the same as a contiguous 2D array: rows may have different lengths and separate allocations.
Common mistakes include off-by-one boundaries, using sizeof on a pointer as if it were the original array, and returning a pointer to a local automatic array after its lifetime ends.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.