c / expert
Snippet
Multi-Dimensional Array Subscripting via Pointers to Array Types
Passing multi-dimensional arrays to functions in C often decays matrix parameters into pointers to single rows. By specifying a pointer to a variable-length array type int (*matrix)[cols], C preserves exact two-dimensional indexing syntax while maintaining memory stride awareness based on dynamic run-time column counts.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>void process_matrix(int rows, int cols, int (*matrix)[cols]) {for (int r = 0; r < rows; ++r) {for (int c = 0; c < cols; ++c) {matrix[r][c] = r * cols + c;}}}int main(void) {int grid[3][4];process_matrix(3, 4, grid);printf("Element [2][1] = %d\n", grid[2][1]);return 0;}
Breakdown
1
void process_matrix(int rows, int cols, int (*matrix)[cols])
Declares matrix parameter as pointer to array of 'cols' integers to maintain 2D subscripting logic.
2
matrix[r][c] = r * cols + c;
Accesses dynamic array element using native double bracket subscript syntax.