pointers-memory · intermediate · ~25 min

Allocate and free a dynamic 2-D array

Two-level allocation; matching free order.

Challenge

Implement two functions:

  • int **alloc_2d(size_t rows, size_t cols) — returns a pointer to an array of rows int* pointers, each pointing to a cols-element int array. Zero-initialized.
  • void free_2d(int **a, size_t rows) — frees the whole structure.

Why this matters

True 2-D allocation in C is its own subject. Two conventions exist: 'array of pointers' (rough but flexible) and 'flat with stride math' (cache-friendly). Knowing both shapes prevents endless segfaults.

Input format

rows, cols small positive sizes.

Output format

See API.

Constraints

Use calloc to zero-initialize.

Starter code

#include <stddef.h>
int **alloc_2d(size_t rows, size_t cols);
void free_2d(int **a, size_t rows);

Common mistakes

Freeing the outer array first, leaking the rows; forgetting to free a NULL-marked tail; allocating rows*cols ints in one block but accessing them as a[i][j] (only works if you actually set up the pointers).

Edge cases to handle

rows or cols == 0 — must not crash. Allocation failure mid-way — clean up partial state.

Complexity

O(rows * cols) to zero-init.

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.