Arrays & Strings · beginner · ~10 min

Multi-dimensional arrays

Work with 2D arrays in row-major layout.

Lesson

int grid[3][4] is an array of 3 arrays of 4 ints — 12 ints in row-major order in memory. grid[r][c] walks rows × columns. The inner dimension must be a constant (or a variable-length array, C99+).

Passing a 2D array to a function requires knowing the inner dimension at compile time: void f(int g[][4], int rows).

Code examples

int g[2][3] = { {1,2,3}, {4,5,6} };
for (int r=0; r<2; r++)
    for (int c=0; c<3; c++) printf("%d ", g[r][c]);

Common mistakes

  • Confusing rows and columns: in C, [r][c] is row r, column c.
  • Trying to declare int g[][] as a function parameter — the inner size must be known.