Multidim array pointer
- C course
- Beginner
- Lesson 81/116
- 5 min
Learn to pass multidimensional arrays as pointers.
Multidimensional arrays
In C a two-dimensional array is an array of arrays. int m[2][3] is a table with two rows and three columns. In memory the rows sit side by side.
int m[2][3] = {{1, 2, 3},
{4, 5, 6}};
printf("%d", m[1][2]); /* 6 */The first index selects the row, the second the column. m[1][2] is the third column of the second row.
Nested loop traversal
To walk a two-dimensional array you use two nested for loops. The outer loop walks rows, the inner loop walks columns.
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", m[i][j]);
}
printf("\n");
}This pattern writes each row to one output line. A newline is added at the end of each row.
Practice Print a two-dimensional array
Define int m[2][3] = {{1, 2, 3}, {4, 5, 6}};. With a for loop print each row as printf("%d %d %d\n", m[i][0], m[i][1], m[i][2]);. The loop runs while i < 2. Output should be 1 2 3 and 4 5 6.
Starter code
#include <stdio.h>
int main(void) {
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
/* print each row as three numbers with a for loop */
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 2; i++) {
printf("%d %d %d\n", m[i][0], m[i][1], m[i][2]);
}
return 0;
}Expected output
1 2 3 4 5 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Second row, third column
int m[2][3] = {{1,2,3},{4,5,6}};
printf("%d", m[____][2]); /* prints 6 */
int m[2][3] = {{1,2,3},{4,5,6}};
printf("%d", m[1][2]); /* prints 6 */
Explanation: m[1][2] is the third column of the second row (6).
2 int m[2][3]; m[1][1] is which?
- First element of first row
- Second element of second row Correct answer
- Second element of third row
- First element of second row
Explanation: m[1][1] is the second column (index 1) of the second row (index 1).
3 Match indices
| Term | Meaning |
|---|---|
m[0][0] |
first row first column |
m[1][2] |
second row third column |
m[i][j] |
row i column j |
int m[2][3] |
two-dimensional array |