Example 1 — A 3 x 4 grid with row pointers
Fill, print, and free every row.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int rows = 3, cols = 4;
int **m = malloc(rows * sizeof *m);
if (!m) return 1;
for (int r = 0; r < rows; r++) {
m[r] = malloc(cols * sizeof **m);
if (!m[r]) return 1;
for (int c = 0; c < cols; c++) m[r][c] = r * cols + c;
}
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) printf("%2d ", m[r][c]);
printf("\n");
}
for (int r = 0; r < rows; r++) free(m[r]);
free(m);
return 0;
} How It Works
mis an array ofrowspointers, each pointing to a row ofcolsints.- Value at
(r, c)isr * cols + c. - Free every row first, then the pointer array.
