C Multidimensional Arrays

So far we have used arrays that store a simple list of values. A multidimensional array lets you store data in a grid, like rows and columns in a table. The most common type is the two-dimensional array, which is perfect for things like a seating chart, a game board, or a spreadsheet.

Creating a 2D Array

A two-dimensional array uses two sets of square brackets. The first number is the count of rows and the second is the count of columns. You can think of it as an array whose elements are themselves arrays.

Declaring a 2D array

#include <stdio.h>

int main() {
  int grid[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
  };
  printf("Row 0, Column 2: %d\n", grid[0][2]);
  printf("Row 1, Column 0: %d\n", grid[1][0]);
  return 0;
}
Note: Just like one-dimensional arrays, both indexes start at 0. In grid[2][3] the valid rows are 0 and 1, and the valid columns are 0, 1, and 2.

Accessing and Changing Values

To reach a value you give both its row and its column. Changing a value works the same way: pick the exact spot with two indexes and assign a new value to it.

Updating one cell

#include <stdio.h>

int main() {
  int grid[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
  };
  grid[1][2] = 99;
  printf("Updated value: %d\n", grid[1][2]);
  return 0;
}

Looping Through a 2D Array

To visit every value in a grid, use one loop inside another. The outer loop walks through the rows and the inner loop walks through the columns of each row. This pattern is called a nested loop.

Printing the whole grid

#include <stdio.h>

int main() {
  int grid[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
  };
  for (int row = 0; row < 2; row++) {
    for (int col = 0; col < 3; col++) {
      printf("%d ", grid[row][col]);
    }
    printf("\n");
  }
  return 0;
}
  • The first bracket is always the row.
  • The second bracket is always the column.
  • You can add more dimensions, such as grid[2][3][4], but 2D arrays cover most everyday needs.
  • When leaving the first size blank in an initializer, C counts the rows for you, but you must always state the column count.
Note: Reading a grid feels natural if you always say row first, then column. Mixing up the order is one of the most common beginner mistakes with 2D arrays.