C ยท Chapter 18 of 45

C Multidimensional Arrays

A multidimensional array stores data in more than one dimension, like a table of rows and columns. The most common form is a two-dimensional array, declared with two sizes in square brackets.

Multidimensional arrays are useful for representing grids, matrices, images, and other tabular data structures.

Syntax
type name[rows][cols] = {{...}, {...}};

Declaring 2D arrays

A 2D array is declared as `int grid[rows][cols];`. Internally, it's stored as contiguous memory in row-major order, meaning each row's elements are stored one after another.

Accessing elements

An element is accessed using two indexes, like `grid[1][2]` for the row-1, column-2 element. Nested for loops are the standard way to visit every element.

Example 1 (c)
#include <stdio.h>

int main() {
  int grid[2][2] = {{1, 2}, {3, 4}};
  printf("%d\n", grid[1][0]);
  return 0;
}
Output
3

grid[1][0] accesses row index 1, column index 0, which holds 3.

Example 2 (c)
#include <stdio.h>

int main() {
  int grid[2][2] = {{1, 2}, {3, 4}};
  for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 2; j++) {
      printf("%d ", grid[i][j]);
    }
  }
  printf("\n");
  return 0;
}
Output
1 2 3 4 

Nested loops visit every row and column of the 2D array in order.

Key points

  • 2D arrays are declared with two sizes: rows and columns.
  • Elements are accessed with two indexes, e.g. grid[row][col].
  • C stores 2D arrays in row-major order in memory.
  • Nested loops are the standard way to process every element.
๐Ÿ’ก Note: You can extend the same idea to three or more dimensions, though readability drops quickly beyond 2D.

๐Ÿ“ Quick Quiz

1. How do you declare a 2D array of 3 rows and 4 columns?

2. How are 2D arrays typically stored in memory in C?

3. How do you access the element at row 2, column 3?