Table of Contents
Individual elements of a two-dimensional array are accessed using two indices: the first specifies the row, and the second specifies the column. Both indices start at 0.
#include <stdio.h>
int main(void)
{
int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
printf("First row, second column: %d\n", matrix[0][1]);
printf("Second row, third column: %d\n", matrix[1][2]);
matrix[0][1] = 99;
printf("Updated element: %d\n", matrix[0][1]);
return 0;
}
Example Output #
First row, second column: 20
Second row, third column: 60
Updated element: 99
Explanation #
The declaration creates an array with two rows and three columns:
int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
The expression matrix[0][1] accesses the element in the first row and second column. The expression matrix[1][2] accesses the element in the second row and third column.
Element Index Reference #
| Expression | Row index | Column index | Value |
|---|---|---|---|
matrix[0][0] |
0 | 0 | 10 |
matrix[0][1] |
0 | 1 | 20 |
matrix[0][2] |
0 | 2 | 30 |
matrix[1][0] |
1 | 0 | 40 |
matrix[1][1] |
1 | 1 | 50 |
matrix[1][2] |
1 | 2 | 60 |
A nested loop can access every element:
for (int row = 0; row < 2; row++)
{
for (int col = 0; col < 3; col++)
{
printf("%d ", matrix[row][col]);
}
printf("\n");
}
The row index must remain between 0 and 1, and the column index between 0 and 2. Accessing an element outside either dimension results in undefined behavior.