c / expert
Snippet
Pointers to Variable Length Arrays (VLA)
Using a pointer to an array with a variable size (VLA) as a function parameter allows for natural multidimensional indexing (matrix[i][j]) while maintaining type safety. Unlike a pointer-to-pointer (int **), this approach ensures the data is contiguous in memory, which is critical for cache efficiency and direct mapping to row-major layouts.
snippet.c
c
1
2
3
4
5
void process_matrix(int rows, int cols, int (*matrix)[cols]) {for (int i = 0; i < rows; i++) {matrix[i][0] = i * cols;}}
Breakdown
1
int (*matrix)[cols]
Defines a pointer to an array of 'cols' integers, where 'cols' is determined at runtime.
2
matrix[i][0]
Uses pointer arithmetic to skip exactly 'cols' integers per row index increment.