Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 135 ยท Arrays and Strings

Multidimensional Arrays

Work with 2D and 3D arrays in C - nested initializers, row-major memory layout, passing matrices to functions, variable-length arrays, and allocating 2D arrays.

Some data has more than one dimension. A spreadsheet has rows and columns, a game board has squares in a grid, an image has pixels in rows, and a weekly timetable has days and hours. C models this with multidimensional arrays: arrays whose elements are themselves arrays.

In this lesson you'll declare and initialize 2D arrays, learn exactly how they're laid out in memory (row by row), loop over them, and pass them to functions, which is where most people get stuck. You'll also meet variable-length arrays (VLAs), which let a function work with matrices of any size, and see how to allocate a 2D array on the heap in a single block.

Declaring a 2D array

A 2D array declaration has two sizes: the number of rows, then the number of columns.

C
int grid[3][4];   // 3 rows, 4 columns: 12 ints

Read it as "grid is an array of 3 elements, each of which is an array of 4 ints". You access an element with two subscripts, row first: grid[1][2] is row 1, column 2. Both indexes start at 0, so the valid range is grid[0][0] to grid[2][3].

You initialize a 2D array with nested braces, one inner list per row:

C A 2D array of monthly sales

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output:

TEXT
        Q1   Q2   Q3   Q4  total
store 0  120  135  150  170    575
store 1   90   80  110  125    405
store 2  200  190  210  260    860
quarter  410  405  470  555 
sizeof sales = 48 bytes, sizeof sales[0] = 16 bytes
rows = 3, columns = 4

sizeof sales is the whole table: 12 ints of 4 bytes each. sales[0] is one row, an array of 4 ints, so it's 16 bytes. That's why the two sizeof divisions work:

  • sizeof sales / sizeof sales[0] = 48 / 16 = 3 rows
  • sizeof sales[0] / sizeof sales[0][0] = 16 / 4 = 4 columns

The nested loops show the two directions you'll traverse a grid: row by row (outer loop over rows) for per-store totals, and column by column (outer loop over columns) for per-quarter totals.

Initializer rules

The same rules as for one-dimensional arrays apply, one level deeper:

C
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};   // fully specified
int b[2][3] = {{1}, {4, 5}};            // missing elements are 0: {1,0,0}, {4,5,0}
int c[2][3] = {0};                      // all zeros
int d[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};   // rows counted: 3
int e[3][3] = {[1][1] = 5};             // designated: only the center is 5

You may omit only the first size (the number of rows). The column count is part of the element type, so the compiler must know it. int f[][] = ... is an error.

You can also write a 2D initializer without inner braces, {1, 2, 3, 4, 5, 6}, and the values fill the array row by row. It works, but the nested form shows the shape and lets missing values be zero per row, so prefer it.

Row-major layout

Memory is one long line of bytes, so the compiler has to flatten the grid. C stores 2D arrays in row-major order: all of row 0, then all of row 1, and so on, with no gaps.

TEXT
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};

           row 0                 row 1
     +-----+-----+-----+-----+-----+-----+
     |  1  |  2  |  3  |  4  |  5  |  6  |
     +-----+-----+-----+-----+-----+-----+
     m[0][0] m[0][1] m[0][2] m[1][0] m[1][1] m[1][2]

So element m[r][c] sits at position r * COLUMNS + c from the start. This next program proves it by printing each element's offset in bytes from the start of the array:

C Seeing row-major order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The offsets go 0, 4, 8, 12, 16, 20: each element is 4 bytes after the previous one, and row 1 starts right where row 0 ends. (%td prints a ptrdiff_t, the type of a pointer difference.)

Row-major order matters for speed. When your loops visit elements in memory order (rows on the outside, columns on the inside), the processor reads memory sequentially and its cache works well. Swapping the loops to walk down columns of a large matrix jumps through memory and can be several times slower. When you can choose, make the last index change fastest.

Even though the layout is contiguous, indexing past the end of a row (m[0][3] to mean m[1][0]) is technically undefined behavior: each row is its own array as far as the bounds rules go. If you want to treat the data as flat, use a real 1D array with r * cols + c indexing, as the example does.

Column-major order, for comparison

C is row-major, but it is not the only choice. Fortran, MATLAB, R and many numerical libraries are column-major: all of column 0 comes first, then column 1, and so on. The element (r, c) then sits at c * ROWS + r. This matters when C code exchanges matrices with such libraries (BLAS and LAPACK are column-major): you either transpose the data or index it the column-major way yourself. The program below stores one 3 by 4 grid both ways and prints the raw memory order.

C Row-major versus column-major storage

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Both arrays describe the same grid (1 2 3 4 on the first row), but the bytes differ: the column-major copy lists 1 5 9 first, which is the first column. With column-major data the cache-friendly loop has the row index on the inside.

Passing 2D arrays to functions

Like a 1D array, a 2D array decays to a pointer to its first element when you pass it. But its first element is a row, so it decays to a pointer to an array of columns: int (*)[3] for an int[2][3]. The column count is part of that type, so the function must know it. These parameter declarations are equivalent:

C
void print_matrix(int rows, int m[][3]);
void print_matrix(int rows, int m[2][3]);   // the 2 is ignored, the 3 is not
void print_matrix(int rows, int (*m)[3]);   // pointer to array of 3 ints

The parentheses in int (*m)[3] matter: int *m[3] would be an array of three pointers, a different type. A plain int ** is also wrong. A 2D array is not an array of pointers, and passing one where int ** is expected is a compile error (or, with casts, a crash).

With a fixed column count, functions work only for that width:

C
#define COLS 3
void scale(int rows, int m[][COLS], int factor);

That's fine for things that never change size (a 3ร—3 transform, an 8ร—8 chessboard), but a general matrix function needs something more flexible.

Variable-length arrays

C99 introduced variable-length arrays (VLAs): arrays whose size is computed at run time. Their most useful form is in function parameters, where they let one function handle matrices of any shape:

C
void print_matrix(size_t rows, size_t cols, const int m[rows][cols]);

The size parameters must come before the array, because the array's type uses them. Inside, m[r][c] works exactly as with a fixed-size array, and the compiler computes r * cols + c for you.

C Matrix functions with VLA parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints the product 58 64 / 139 154 and the transpose 1 4 / 2 5 / 3 6. The same print_matrix handled a 2ร—2 and a 3ร—2 matrix. Without VLA parameters you'd need either one function per width or manual flat indexing.

VLAs as local variables, and their risks

You can also declare a local array with a run-time size:

C
void process(size_t n)
{
    double samples[n];   // VLA on the stack
    ...
}

This is convenient but dangerous. Local VLAs live on the stack, which is small (often 1 to 8 MB). If n comes from input and is large, the program overflows the stack and crashes, and there's no way to detect the failure beforehand, unlike malloc returning NULL. For that reason many coding standards (including the Linux kernel's) ban local VLAs, and C11 made VLA support optional: a compiler that defines __STDC_NO_VLA__ doesn't have them. MSVC never supported them.

C23 clarified the split: variably modified types, like the m[rows][cols] parameters above and pointers to VLAs, are mandatory again, while automatic (stack) VLAs remain optional. GCC and Clang support both. Use VLA parameters freely; avoid large stack VLAs.

Allocating a 2D array on the heap

When the size is known only at run time and could be large, allocate the matrix with malloc. The cleanest way uses a pointer to a VLA row, so you still get m[r][c] indexing and a single contiguous block:

C A heap-allocated 2D array in one block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With the input 4 5 it prints a 4ร—5 multiplication table and one block of 80 bytes. sizeof *m is the size of one row (cols * sizeof(int)), so rows * sizeof *m is the whole matrix. Change the Input box to try other sizes.

If you need code that compiles without VLA support (for example with MSVC), allocate a flat int *data = malloc(rows * cols * sizeof *data); and index it as data[r * cols + c]. Another approach you'll see is an array of row pointers (int **), each row allocated separately. It allows rows of different lengths ("jagged" arrays) but takes rows + 1 allocations, scatters rows through memory, and needs a loop to free. Pointers to Pointers covers that design.

More dimensions, and arrays of strings

Nothing stops at two. A 3D array is an array of 2D arrays:

C
// temperature[day][hour][sensor]
double temperature[7][24][4];
temperature[2][13][0] = 21.5;   // day 2, 1 pm, sensor 0

The layout is still row-major (the last index changes fastest), and when passing it to a function, every size except the first must be known: void analyze(size_t days, double t[days][24][4]).

A very common 2D array is a table of strings: each row is a fixed-size char array holding one string.

C
char weekdays[7][10] = {
    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday",
};
printf("%s\n", weekdays[2]);   // Wednesday

Each row needs room for the longest name plus the terminating '\0' ("Wednesday" is 9 letters, so 10 bytes). You'll learn about that terminator in the next lesson, Strings.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. For int t[4][6];, what is sizeof t / sizeof t[0]?

    sizeof t is the whole array (24 ints) and sizeof t[0] is one row (6 ints), so the division gives the number of rows, 4.
  2. 2. In int m[3][5], which element is stored immediately after m[0][4] in memory?

    C stores arrays in row-major order. After the last element of row 0 comes the first element of row 1.
  3. 3. Which parameter declaration can receive an int grid[8][8]?

    A 2D array decays to a pointer to its first row, an array of 8 ints, which is int (*)[8]. int ** and int *[8] are different types, and int grid[][] is invalid because the column count is required.
  4. 4. What does this print? int a[2][3] = {{1}, {4, 5}}; printf("%d %d", a[0][2], a[1][1]);

    Row 0 is {1, 0, 0} and row 1 is {4, 5, 0}, so a[0][2] is 0 and a[1][1] is 5.
  5. 5. Why are large local VLAs like double samples[n] risky?

    Stack space is limited and a VLA can't report failure the way malloc returns NULL. Use VLA parameters freely, but allocate big buffers with malloc.

Summary

  • int grid[ROWS][COLS] is an array of rows; access elements with grid[r][c], both indexes starting at 0.
  • Initialize with nested braces; missing elements are 0, and only the first size may be omitted.
  • C stores multidimensional arrays in row-major order: m[r][c] is at flat position r * COLS + c. Loop with the last index innermost for speed.
  • A 2D array decays to a pointer to its first row (int (*)[COLS]), not to int **; functions must know every size but the first.
  • VLA parameters (int m[rows][cols], sizes first) let one function handle any matrix shape.
  • Local VLAs are optional since C11 and risky for big sizes; allocate large matrices with malloc, ideally as one block via int (*m)[cols].
  • A char names[N][LEN] array stores a table of fixed-size strings.

Next: Strings, where you'll learn how C represents text with char arrays and a terminating zero.