Sub topic 8
Two-Dimensional Arrays and Pointer Equivalents
Assume you know basic C arrays, functions, pointer dereferencing, and pointer arithmetic. This chapter focuses on how a two-dimensional array is stored and how C represents it through pointer types.
Memory layout
A two-dimensional array is an array whose elements are one-dimensional arrays. For example:
int a[2][3] = {
{10, 20, 30},
{40, 50, 60}
};This has two rows and three columns. The elements occupy contiguous memory in row-major order:
10 20 30 40 50 60The expression a[i][j] means “row i, column j.” Its pointer form is:
a[i][j] == *(*(a + i) + j)The first a + i moves by complete rows. Each row contains three int values, so a + 1 moves past one row, not one integer.
Pointer equivalents
For int a[2][3]:
ausually converts toint (*)[3], a pointer to an array of three integers.a + 1points to the next row.*(a + i)is rowi, which can then convert toint *.*(*(a + i) + j)accesses one integer.
The type int ** is different. It means a pointer to a pointer to an integer. It does not describe one contiguous two-dimensional array. An int ** might point to separately allocated rows, but it cannot safely replace int (*)[3].
Passing a two-dimensional array
When passing an array to a function, C needs the column count to calculate row addresses. The first dimension may be omitted:
#include <stdio.h>
void print_matrix(int a[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
}
int main(void) {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
print_matrix(a, 2);
return 0;
}The parameter int a[][3] is adjusted to int (*a)[3]. Therefore, the function knows each row has three integers.
sizeof a in the caller gives the total array size. Inside the function, sizeof a gives the size of a pointer, because the parameter is no longer an array object.
Exercise
For int x[3][4], what does x + 2 point to, and what is the pointer form of x[1][3]?
Show answer
x + 2 points to the third row, whose type is int (*)[4]. The pointer form of x[1][3] is *(*(x + 1) + 3).