c / expert
Snippet
Dynamic Two-Dimensional Array Allocation via Pointer-to-Array Types
Using C99 pointer-to-variable-length-array types enables dynamic allocation of multi-dimensional arrays in a single contiguous memory block. This approach avoids double pointer indirection and multiple malloc calls while supporting conventional double subscript indexing syntax.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>#include <stdlib.h>int (*allocate_matrix(size_t rows, size_t cols))[cols] {int (*matrix)[cols] = malloc(rows * sizeof(*matrix));if (!matrix) return NULL;for (size_t r = 0; r < rows; r++) {for (size_t c = 0; c < cols; c++) {matrix[r][c] = (int)(r + c);}}return matrix;}
Breakdown
1
int (*allocate_matrix(size_t rows, size_t cols))[cols]
Uses C99 variable-length array syntax to declare a function returning a pointer to an array of size cols.
2
int (*matrix)[cols] = malloc(rows * sizeof(*matrix));
Allocates one contiguous block sized for all rows where each element is an array of cols elements.
3
matrix[r][c] = (int)(r + c);
Indexes elements directly using standard 2D bracket syntax without double pointer dereferencing.