c / expert
Snippet
Multidimensionale Array-Zeiger-Flattenung und optimierter Schrittweiten-Zugriff
Das Allokieren zweidimensionaler Arrays als Array von Zeigern (z. B. double**) führt zu Zeiger-Indirektion und Fragmentierung, was die Auslastung der CPU-Cache-Zeilen verschlechtert. Das Linearisieren eines mehrdimensionalen Arrays in einen einzelnen zusammenhängenden Speicherblock mit berechneter Schrittweite optimiert die räumliche Lokalität und maximale Hardware-Performance.
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;}
Erklärung
1
Matrix *m = malloc(sizeof(Matrix) + sizeof(double) * rows * cols);
Allokiert einen einzelnen zusammenhängenden Speicherblock für Metadaten und flachen 2D-Element-Speicher.
2
return m->data[r * m->cols + c];
Berechnet den 1D-Speicher-Offset für 2D-Indizes (Zeile * Spaltenbreite + Spalte) ohne verschachtelte Zeiger.