Multidimensional Arrays

Multidimensional Arrays in C: You think of as a table — three rows, four columns, twelve cells. The machine does not.

The Analogy: A Spreadsheet Stored on One Long Shelf

You think of grid[3][4] as a table — three rows, four columns, twelve cells. The machine does not. It has one straight shelf of twelve boxes, and it stores row 0 first, then row 1 behind it, then row 2. The rectangle exists only in the notation.

That storage order is called row-major, and it explains almost everything about how these arrays behave. grid[1][2] is not found by walking down and across; it is found by arithmetic — skip one full row of four, then step two more, so it is box number six on the shelf. Rows are guaranteed to be adjacent with no gaps, which is why the whole grid can be copied with a single memcpy and why the compiler must be told the column count before it can index anything.

It also explains a performance fact you will meet later: walking a large grid row by row reads the shelf in order, while walking it column by column jumps four boxes at a time and defeats the cache.


Syntax or Core Structure

#include <stdio.h>

#define ROWS 3
#define COLS 4

int main(void) {
    int grid[ROWS][COLS] = {
        { 1,  2,  3,  4 },
        { 5,  6,  7,  8 },
        { 9, 10, 11, 12 }
    };

    for (size_t r = 0; r < ROWS; r++) {
        for (size_t c = 0; c < COLS; c++) {
            printf("%4d", grid[r][c]);
        }
        putchar('\n');
    }

    printf("sizeof grid       = %zu\n", sizeof grid);
    printf("sizeof grid[0]    = %zu\n", sizeof grid[0]);
    printf("sizeof grid[0][0] = %zu\n", sizeof grid[0][0]);
    return 0;
}

Output (on a typical build where int is 4 bytes):

   1   2   3   4
   5   6   7   8
   9  10  11  12
sizeof grid       = 48
sizeof grid[0]    = 16
sizeof grid[0][0] = 4

Those three sizeof values are the whole model in numbers. The grid is 48 bytes — twelve ints, contiguous. grid[0] is not an int; it is an entire row, sixteen bytes of it. Only grid[0][0] is a single element. So the row count is sizeof grid / sizeof grid[0] and the column count is sizeof grid[0] / sizeof grid[0][0].

The flat equivalence

Because the layout is row-major, these two expressions name the same box:

int *flat = &grid[0][0];

grid[1][2]            /* 7 */
flat[1 * COLS + 2]    /* 7 -- the same byte, reached by hand */

row * COLS + col is exactly the arithmetic the compiler performs for you. Knowing the formula matters because when the dimensions are only known at run time, writing it out by hand is often the cleanest option available.

Initialiser forms

int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };   /* clearest: braces per row */
int b[2][3] = { { 1 }, { 4 } };               /* 1,0,0 / 4,0,0 */
int c[2][3] = { 0 };                          /* all six zeroed */
int d[2][3] = { 1, 2, 3, 4, 5, 6 };           /* legal, fills row-major */
int e[][3]  = { { 1, 2, 3 }, { 4, 5, 6 } };   /* rows counted; COLS required */

The d form works but is a maintenance trap — insert one value and every subsequent row shifts by one column, silently. Keep the inner braces. And note e: the first dimension can be left for the compiler to count, the others never can.


Technical Depth: Passing a Grid to a Function

A 2D array decays like a 1D one, but into something less familiar. grid becomes a pointer to a row — type int (*)[COLS] — not int **. The column count is baked into that type, because without it the compiler cannot compute row * COLS + col. Hence the three viable signatures:

SignatureNeedsGood forLimit
void f(int g[][COLS], size_t rows)COLS fixed at compile timefixed-width tablesone width only
void f(size_t rows, size_t cols, int g[rows][cols])C99 variable-length array parametersany size, natural g[r][c] syntaxoptional in C11 and later; MSVC does not support it
void f(int *g, size_t rows, size_t cols)you index g[r * cols + c]maximum portability, heap gridsmanual arithmetic
/* Fixed width: the compiler knows how far one row is. */
int row_total(const int g[][COLS], size_t r) {
    int sum = 0;
    for (size_t c = 0; c < COLS; c++) sum += g[r][c];
    return sum;
}

/* C99 variable-length parameters: dimensions come first, on purpose. */
int cell(size_t rows, size_t cols, const int g[rows][cols], size_t r, size_t c) {
    (void)rows;
    return g[r][c];
}

/* Flat: works for any dimensions, on the stack or the heap. */
int flat_cell(const int *g, size_t cols, size_t r, size_t c) {
    return g[r * cols + c];
}

The middle form must take the dimensions before the array, because they appear in the array's own type. The last form is what you will end up writing for anything malloced, and it is the one that never surprises anyone.

Why int ** does not work

void wrong(int **g);          /* expects an array OF POINTERS */
int grid[3][4];
/* wrong(grid);                 does not compile, and rightly so */

int ** means "pointer to a pointer to int", which describes a completely different layout: an array of row pointers, each pointing at a separately allocated row that could be anywhere in memory. A true 2D array is one solid block. The types differ because the layouts differ, and forcing the conversion with a cast produces a program that reads garbage addresses.

Loop order and the cache

/* Fast: consecutive addresses, one cache line serves several elements. */
for (size_t r = 0; r < ROWS; r++)
    for (size_t c = 0; c < COLS; c++)
        sum += grid[r][c];

/* Slow on large grids: each step jumps COLS elements forward. */
for (size_t c = 0; c < COLS; c++)
    for (size_t r = 0; r < ROWS; r++)
        sum += grid[r][c];

Both are correct and both visit every element once. On a 3x4 grid the difference is unmeasurable; on a 2000x2000 grid the row-major version can be several times faster. The habit to build now is: innermost loop varies the last index.

More dimensions

int cube[2][3][4]; follows the identical rule — 24 contiguous ints, with the last index varying fastest. sizeof cube[0] is one 3x4 slab, sizeof cube[0][0] is one row of four. Beyond three dimensions, most codebases switch to a flat array plus an index helper, because the declarations stop being readable.


Real World Example: A Gradebook With Row and Column Totals

Students down the side, assignments across the top. Row averages tell you how each student is doing; column averages tell you which assignment was too hard. It is the canonical use of a 2D array, and the interesting part is that the two aggregations traverse the same storage in opposite directions.

#include <stdio.h>

#define STUDENTS 4
#define TASKS    3

int main(void) {
    const char *names[STUDENTS] = { "Ada", "Brian", "Chen", "Dara" };
    const char *tasks[TASKS]    = { "A1", "A2", "A3" };

    int marks[STUDENTS][TASKS] = {
        { 88,  92,  79 },
        { 70,  65,  80 },
        { 95,  91, 100 },
        { 60,  75,  72 }
    };

    /* Header */
    printf("%-8s", "");
    for (size_t t = 0; t < TASKS; t++) printf("%6s", tasks[t]);
    printf("%8s\n", "avg");

    /* One row per student: sum across the row (row-major, cheap). */
    int grand = 0;
    for (size_t s = 0; s < STUDENTS; s++) {
        int row = 0;
        printf("%-8s", names[s]);
        for (size_t t = 0; t < TASKS; t++) {
            printf("%6d", marks[s][t]);
            row += marks[s][t];
        }
        grand += row;
        printf("%8.2f\n", (double)row / TASKS);
    }

    /* One footer cell per task: sum down each column. */
    printf("\n%-8s", "avg");
    for (size_t t = 0; t < TASKS; t++) {
        int col = 0;
        for (size_t s = 0; s < STUDENTS; s++) col += marks[s][t];
        printf("%6.2f", (double)col / STUDENTS);
    }
    printf("%8.2f\n", (double)grand / (STUDENTS * TASKS));

    return 0;
}

Output:

            A1    A2    A3     avg
Ada         88    92    79   86.33
Brian       70    65    80   71.67
Chen        95    91   100   95.33
Dara        60    75    72   69.00

avg      78.25 80.75 82.75   80.58

Check one figure by hand to convince yourself: Ada's marks total 259, and 259 divided by 3 is 86.33. Column A1 totals 313 across four students, giving 78.25. The grand total is 967 over twelve marks, which is 80.58 — and it is worth noting that summing the row totals and summing the column totals must give the same 967, which makes a free consistency check when a report looks wrong.

Two things generalise from this. The row pass accumulates while it prints, because it is already walking that row — no second traversal needed. The column pass cannot do that, so it gets its own nested loop after the table; when a grid is large enough for that to matter, you keep an array of column accumulators and finish both aggregations in a single row-major pass.


Common Mistakes

  1. Writing grid[r, c]. That is the comma operator, not a two-index subscript — it evaluates r, discards it, and subscripts with c, giving you a whole row where you wanted a cell. C requires grid[r][c].
  1. Declaring the parameter as int **. A 2D array is one contiguous block, not an array of row pointers. Use int g[][COLS], a variable-length parameter, or a flat int *.
  1. Omitting the column size in a parameter. int g[][] will not compile. Every dimension except the first must be known, because the compiler needs them to do the index arithmetic.
  1. Swapping the indices. marks[t][s] instead of marks[s][t] is a compile error on a rectangular grid, but on a square one it compiles and silently transposes your data. Name the loop variables after what they mean.
  1. Iterating column-major on large grids. Correct but cache-hostile. Keep the last index in the innermost loop.
  1. Flattening the initialiser. int a[3][4] = { 1, 2, ... }; without inner braces means inserting a single value shifts every later row. Brace each row.
  1. Misreading sizeof grid[0]. It is the size of one whole row, not one element. The element is grid[0][0].
  1. Assuming rows can be swapped by assignment. grid[0] = grid[1] does not compile — a row is an array, and arrays do not assign. Use memcpy(grid[0], grid[1], sizeof grid[0]);.

Best Practices

  • Name both dimensions with #define or an enum and derive every loop bound and declaration from those names.
  • Keep the innermost loop on the last index, always. It costs nothing to make it a reflex and it pays off on big data.
  • Brace initialisers row by row so the source layout matches the logical shape.
  • Pass both dimensions explicitly, even when one is fixed in the type. The reader should not have to look up COLS to understand the call.
  • Use int g[][COLS] for genuinely fixed-width tables and a flat int * with r * cols + c for anything sized at run time. Reach for variable-length parameters only when you know every target compiler supports them.
  • Use memcpy with sizeof grid to copy a whole grid and sizeof grid[0] to copy one row — never a hand-written double loop.
  • Give the indices meaningful names — student and task, or r and c — rather than i and j, which are easy to transpose.
  • Cross-check aggregations when a grid has both row and column totals. They must agree, and that agreement is the cheapest test you will ever write.

Practice Exercises

  1. Prove the layout. Declare int g[3][4] filled 1 to 12, then print all twelve values using only int *flat = &g[0][0]; and a single loop with one index. Confirm the order matches the row-by-row reading, and print sizeof g, sizeof g[0] and sizeof g[0][0] with an explanation of each number.
  1. Transpose it. Write a function that fills int out[COLS][ROWS] from int in[ROWS][COLS] so that out[c][r] == in[r][c], then print both grids. Now try to do it in place on a non-square grid and explain in one sentence why the declaration itself stops you.
  1. All three signatures. Write grid_sum three times: once taking const int g[][COLS], once with C99 variable-length parameters, and once flat with const int *g, size_t rows, size_t cols. Call all three on the same grid, confirm they return the same total, and note which one you would ship and why.
  1. Extend the gradebook. Add a fifth student and a fourth assignment to the example, changing only the two #define lines and the data. Then add a column of letter grades derived from each row average, and a final line reporting which assignment had the lowest average — printing the assignment's name, not its index.