Course contentsShow
← C
Lesson 504 of 1,2197. PointersFree lesson

Dynamic 2D array structures

Dynamic 2D array structures

What you'll learn: How to use pointers to pointers to create flexible, grid-like memory structures that can resize at runtime.

The "Array of Folders" Analogy

In earlier lessons, we used a single pointer to point to a row of data. But what if you don't know how many rows you need until the program is already running? This is where a pointer to a pointer (int **) comes in.

Think of a filing cabinet. A single pointer is like a finger pointing to one specific folder. A pointer to a pointer is like a finger pointing to a list of locations where those folders are kept. This allows you to create a "grid" where each row can even be a different length if you want, offering much more flexibility than a standard fixed-size array.

How it works in memory

To build a dynamic 2D structure, you follow a two-step process:

  1. The Spine: You allocate an array of pointers. Each element in this array will hold the address of a row.
  2. The Ribs: You loop through your "spine" and allocate a separate array for each row.
#include <stdio.h>
#include <stdlib.h>

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

    // 1. Allocate the "spine" (an array of int pointers)
    int **grid = malloc(rows * sizeof(int *));

    // 2. Allocate each "row" individually
    for (int i = 0; i < rows; i++) {
        grid[i] = malloc(cols * sizeof(int));
    }

    // Now you can use it like a normal 2D array!
    grid[1][2] = 50;
    printf("Value at [1][2]: %d\n", grid[1][2]);

    // 3. Clean up (work backwards: rows first, then the spine)
    for (int i = 0; i < rows; i++) {
        free(grid[i]);
    }
    free(grid);

    return 0;
}

Why use this?

Unlike a static array (like int board[3][4]), this structure lives on the heap. This means you can determine the dimensions based on user input or a file size while the program is running. Furthermore, because you are allocating each row separately, the rows don't actually have to be next to each other in your computer's physical memory; the "spine" keeps track of where they are scattered.

Key takeaway

A dynamic 2D array is a pointer to an array of pointers, where each pointer manages its own independently allocated row of data.