Reading history

Dynamic 2D Arrays in C: Three Ways to Allocate

6 min read 0 views

Allocate 2D arrays at run time in C with row pointers, one flat block or a pointer to an array, plus jagged rows and correct freeing.

A fixed 2D array such as int seats[3][4] needs its size when you write the program. To create a grid whose rows and columns are only known at run time, such as a seating plan, a game board or a spreadsheet read from a file, you allocate it on the heap. C offers three common ways to do this, each with its own trade-offs. This lesson shows all three, plus a jagged array whose rows have different lengths.

In this lesson you will learn

  • An array of row pointers, allocated row by row
  • One flat block indexed as r * cols + c
  • A pointer to an array, giving [r][c] syntax with one malloc
  • Jagged arrays with rows of different lengths
  • Freeing each kind correctly, even after a failed allocation

You should know multidimensional arrays, pointers to pointers and dynamic arrays.

Row Pointers and a Flat Block

#include <stdio.h>
#include <stdlib.h>

/* Method 1: an array of row pointers (rows can even differ in length) */
int **make_rows(int rows, int cols) {
    int **m = malloc(rows * sizeof *m);
    if (!m) return NULL;
    for (int r = 0; r < rows; r++) {
        m[r] = malloc(cols * sizeof *m[r]);
        if (!m[r]) {                       /* undo what was allocated so far */
            while (r--) free(m[r]);
            free(m);
            return NULL;
        }
    }
    return m;
}

void free_rows(int **m, int rows) {
    for (int r = 0; r < rows; r++)
        free(m[r]);
    free(m);
}

int main(void) {
    int rows = 3, cols = 4;               /* could come from user input */

    int **seats = make_rows(rows, cols);
    if (!seats) return 1;
    for (int r = 0; r < rows; r++)
        for (int c = 0; c < cols; c++)
            seats[r][c] = (r + 1) * 10 + c;

    puts("Method 1: array of row pointers");
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++)
            printf("%4d", seats[r][c]);
        printf("\n");
    }
    free_rows(seats, rows);

    /* Method 2: one block, index with r * cols + c */
    int *grid = malloc(rows * cols * sizeof *grid);
    if (!grid) return 1;
    for (int r = 0; r < rows; r++)
        for (int c = 0; c < cols; c++)
            grid[r * cols + c] = r * cols + c;

    puts("Method 2: one flat block");
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++)
            printf("%4d", grid[r * cols + c]);
        printf("\n");
    }
    free(grid);
    return 0;
}

Output

Method 1: array of row pointers
  10  11  12  13
  20  21  22  23
  30  31  32  33
Method 2: one flat block
   0   1   2   3
   4   5   6   7
   8   9  10  11
  • Method 1 allocates an array of int *, one per row, then a separate block for each row. You can write seats[r][c] because seats[r] is a pointer to that row’s first element.
  • If any row’s malloc fails, make_rows frees the rows already made, and the pointer array, before returning NULL. This avoids a memory leak on the error path.
  • Freeing takes the reverse order: every row first, then the array of row pointers.
  • Method 2 uses one block of rows * cols integers and calculates the position yourself: row r, column c is at r * cols + c. There is one malloc and one free, and all the data sits together in memory, which is usually faster.

A Pointer to an Array, and Jagged Rows

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int rows = 3, cols = 4;

    /* Method 3: pointer to an array of cols ints - one malloc, real [r][c] syntax */
    int (*table)[cols] = malloc(rows * sizeof *table);
    if (!table) return 1;

    for (int r = 0; r < rows; r++)
        for (int c = 0; c < cols; c++)
            table[r][c] = r * c;

    puts("Method 3: pointer to array (one block, [r][c] indexing)");
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++)
            printf("%3d", table[r][c]);
        printf("\n");
    }
    printf("sizeof *table = %zu bytes (one row of %d ints)\n", sizeof *table, cols);
    free(table);                       /* a single free */

    /* A jagged array: Pascal's triangle, row r has r + 1 numbers */
    int n = 6;
    long **pascal = malloc(n * sizeof *pascal);
    if (!pascal) return 1;
    for (int r = 0; r < n; r++) {
        pascal[r] = malloc((r + 1) * sizeof *pascal[r]);
        if (!pascal[r]) return 1;
        pascal[r][0] = pascal[r][r] = 1;
        for (int c = 1; c < r; c++)
            pascal[r][c] = pascal[r - 1][c - 1] + pascal[r - 1][c];
    }
    puts("Jagged rows: Pascal's triangle");
    for (int r = 0; r < n; r++) {
        printf("%*s", (n - r - 1) * 2, "");
        for (int c = 0; c <= r; c++)
            printf("%4ld", pascal[r][c]);
        printf("\n");
        free(pascal[r]);
    }
    free(pascal);
    return 0;
}

Output

Method 3: pointer to array (one block, [r][c] indexing)
  0  0  0  0
  0  1  2  3
  0  2  4  6
sizeof *table = 16 bytes (one row of 4 ints)
Jagged rows: Pascal's triangle
             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1
   1   5  10  10   5   1
  • Method 3 declares table as a pointer to an array of cols ints. sizeof *table is the size of one whole row, so rows * sizeof *table allocates the entire grid in one block, and table[r][c] works directly. It combines the speed of Method 2 with the easy syntax of Method 1.
  • Method 3 relies on variable-length array types, which are optional in C11. GCC and Clang support them; Microsoft’s compiler does not.
  • Pascal’s triangle is a jagged array: row r holds r + 1 numbers. Only the row-pointer method can do this, because each row is allocated separately with its own length.
  • Each number is the sum of the two above it. %*s takes the field width from an argument, which is used here to indent each row.

Comparing the Three Methods

MethodAllocationsIndexingRows of different length?
Row pointers int **rows + 1m[r][c]Yes
Flat block int *1m[r * cols + c]No
Pointer to array int (*)[cols]1m[r][c]No

Common Mistakes

  1. Freeing only the pointer array in Method 1, which leaks every row.
  2. Freeing the pointer array first, then reading m[r] to free the rows: the pointers are already gone.
  3. Passing an int ** to a function that expects int [][4]. They have different layouts in memory and are not interchangeable.
  4. Mixing up rows and columns in r * cols + c. Multiply the row by the number of columns, not rows.

Practice Exercises

Exercise 1. Using Method 2, write a function that returns the sum of column c of a flat rows x cols grid.

Show answer
int column_sum(const int *grid, int rows, int cols, int c) {
    int sum = 0;
    for (int r = 0; r < rows; r++)
        sum += grid[r * cols + c];
    return sum;
}

Exercise 2. Allocate a lower-triangular jagged array where row r has r + 1 ints, set every value to r, and free it.

Show answer
int n = 4;
int **tri = malloc(n * sizeof *tri);
for (int r = 0; r < n; r++) {
    tri[r] = malloc((r + 1) * sizeof *tri[r]);
    for (int c = 0; c <= r; c++) tri[r][c] = r;
}
for (int r = 0; r < n; r++) free(tri[r]);
free(tri);

Real code should also check each malloc for NULL, as make_rows does.

Frequently Asked Questions

Which method should I use?

Use the flat block or the pointer-to-array method for ordinary rectangular grids: they are faster and easier to free. Use row pointers when rows need different lengths or must be swapped cheaply, for example when sorting rows.

Why not just declare int grid[rows][cols] inside the function?

That creates a variable-length array on the stack. It is fine for small grids, but the stack is limited, often to a few megabytes, and there is no way to detect that it ran out. Large or long-lived grids belong on the heap.

Summary

  • Row pointers allow jagged rows but need one allocation per row.
  • A flat block is one allocation; index it with r * cols + c.
  • A pointer to an array gives [r][c] syntax with a single allocation.
  • Free inner blocks first, then the outer one, and clean up on every error path.

Next: Matrix Operations in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *