c / expert
Snippet
Multidimensional Array Pointer Flattening and Strided Access Optimization
Allocating two-dimensional arrays as arrays of pointers (e.g. double**) introduces pointer indirection and non-contiguous heap memory fragmentation, degrading CPU cache line utilization. Linearizing a multi-dimensional array into a single contiguous block of memory with explicit strided pointer offset calculations improves spatial locality and enables hardware prefetchers to operate at peak throughput.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>#include <stdlib.h>/* Linearized 2D grid allocation for single-heap allocation and cache prefetching */typedef struct {size_t rows;size_t cols;double data[];} Matrix;Matrix* allocate_matrix(size_t rows, size_t cols) {Matrix *m = malloc(sizeof(Matrix) + sizeof(double) * rows * cols);if (!m) return NULL;m->rows = rows;m->cols = cols;return m;}inline static double get_element(const Matrix *m, size_t r, size_t c) {/* Strided access calculation: index = row * cols + col */return m->data[r * m->cols + c];}int main(void) {Matrix *m = allocate_matrix(4, 4);if (m) {m->data[2 * 4 + 3] = 42.5; /* Row 2, Col 3 */printf("Value at (2,3): %.1f\n", get_element(m, 2, 3));free(m);}return 0;}
Breakdown
1
Matrix *m = malloc(sizeof(Matrix) + sizeof(double) * rows * cols);
Allocates a single contiguous memory block accommodating matrix metadata and flat 2D element storage.
2
return m->data[r * m->cols + c];
Computes the exact 1D memory offset for 2D indices (row * stride + col) eliminating pointer pointer dereferences.