Lesson 15 of 31
Multi-dimensional Arrays
Multi-dimensional Arrays
C supports arrays of arrays -- multi-dimensional arrays. The most common is the 2D array:
Declaration
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
This creates a 2-row, 3-column matrix. In memory, the rows are stored contiguously.
Holodeck grids: a 2D array of emitters creating a 3D world. Every
matrix[row][col]is one photon emitter in the grid.
Accessing Elements
int val = matrix[0][2]; // row 0, column 2 = 3
matrix[1][0] = 99; // set row 1, column 0 to 99
Iterating
Use nested loops:
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
printf("%d ", matrix[row][col]);
}
printf("\n");
}
Memory Layout
A 2D array int m[R][C] is laid out as R*C contiguous integers. m[i][j] is at offset (i * C + j) * sizeof(int).
Your Task
Create a 3x3 identity matrix (1s on the diagonal, 0s elsewhere) and print it row by row. Each row should have numbers separated by spaces, followed by a newline.
TCC compiler loading...
Loading...
Click "Run" to execute your code.