C Multidimensional Arrays
An array can have more than one dimension. A two-dimensional array is a table with rows and columns, such as a seating plan, a game board or the marks of several students in several subjects.
Declaring a 2D array
Give the number of rows, then the number of columns. Each row's values go in their own braces.
#include <stdio.h>
int main(void) {
int table[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printf("table[0][0] = %d\n", table[0][0]);
printf("table[1][2] = %d\n", table[1][2]);
return 0;
}table[0][0] = 1 table[1][2] = 6
table[1][2] is row 1, column 2: the third value of the second row. Both indexes start at 0.
Looping over rows and columns
Two nested loops visit every element: the outer loop goes over the rows, the inner loop over the columns of one row.
#include <stdio.h>
int main(void) {
int marks[3][4] = {
{80, 72, 91, 65},
{58, 77, 69, 84},
{93, 88, 79, 90}
};
for (int s = 0; s < 3; s++) {
int total = 0;
printf("Student %d:", s + 1);
for (int sub = 0; sub < 4; sub++) {
printf(" %3d", marks[s][sub]);
total += marks[s][sub];
}
printf(" total %d\n", total);
}
return 0;
}Student 1: 80 72 91 65 total 308 Student 2: 58 77 69 84 total 288 Student 3: 93 88 79 90 total 350
Adding two matrices
In mathematics a table of numbers is a matrix. Adding two matrices adds the elements at the same position:
#include <stdio.h>
int main(void) {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{10, 20}, {30, 40}};
int sum[2][2];
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 2; c++) {
sum[r][c] = a[r][c] + b[r][c];
}
}
for (int r = 0; r < 2; r++) {
printf("%d %d\n", sum[r][0], sum[r][1]);
}
return 0;
}11 22 33 44
How it is stored
In memory a 2D array is one long row of values: first all of row 0, then all of row 1, and so on. That is why, when you pass a 2D array to a function, the number of columns must be given: void print(int t[][4], int rows).
Common mistakes
- Swapping the indexes:
table[col][row]instead oftable[row][col]. Name the loop variablesrowandcolto keep them straight. - Using the wrong limit in the inner loop: the inner loop counts columns, the outer loop rows.
- Going past the last row or column: like any array, indexes run from 0 to size − 1, and C does not check them. Safe mode in the editor catches it.
Arrays can have more than two dimensions too, such as int cube[3][3][3], but two are by far the most common.
Practice exercises
- Print the total of each column of the marks table.
- Build a 3 by 3 tic-tac-toe board of characters filled with
'.', put an'X'in the middle and print it. - Print the multiplication table from 1 to 5 as a 5 by 5 grid stored in a 2D array.