A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
Returning a 2D array from a function requires returning the row-pointer array and ensuring the caller can free everything. The function allocates the pointer array and each row. The caller receives the pointer and the dimensions. The caller is responsible for freeing each row and then the pointer array. The ownership transfer must be documented. Miss one free and you leak. Free in the wrong order and you corrupt.
#include <stdio.h>#include <stdlib.h>int **create_grid(int rows, int cols) {int **grid = malloc(rows * sizeof(int *));if (!grid) return NULL;for (int i = 0; i < rows; i++) {grid[i] = calloc(cols, sizeof(int));if (!grid[i]) {for (int j = 0; j < i; j++) free(grid[j]);free(grid);return NULL;}}for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {grid[i][j] = i * cols + j + 1;}}return grid;}void free_grid(int **grid, int rows) {for (int i = 0; i < rows; i++) {free(grid[i]);}free(grid);}int main(void) {int rows = 3, cols = 4;int **grid = create_grid(rows, cols);if (!grid) return 1;for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {printf("%3d ", grid[i][j]);}printf("\n");}free_grid(grid, rows);return 0;}
The create_grid function handles allocation failure at every level. If row i fails, it frees rows 0 through i-1 and the pointer array. The free_grid function mirrors the allocation: free each row, then free the pointer array. The caller must pass the row count to free_grid because the pointer array does not carry its own length. This is the cost of the row-pointer approach.
The flat-buffer alternative from the pointers module avoids this complexity: one allocation, one free, manual index arithmetic. For functions that return 2D data, the flat buffer is often the cleaner API. The row-pointer approach is better when you need arr[i][j] syntax throughout the codebase. Next: finding array length with sizeof, and why it only works in one place.
Finish the lesson once you have worked through the material. This awards ★ 40 XP.