我目前正在堆上实现一个 N x 2 的 floats
矩阵,如下所示:
float **matrix = malloc(sizeof(float*) * n_cols);
for (int i = 0; i < n_cols; ++i) {
matrix[i] = malloc(sizeof(float) * 2);
}
matrix
的元素在内存中不连续,使得这个数据结构缓存不友好(据我了解)。我正在尝试重写上面的内容以在堆上创建一个真正的二维数组。根据之前的一些 SO 帖子,我尝试了以下操作:
float (*matrix)[2] = malloc(sizeof(float) * n_cols * 2);
但是,当我运行我的代码时,这会导致段错误。
最佳答案
如果你希望整个数组是连续的,那么你需要如下声明它。
float *matrix = malloc(n1 * n2 * sizeof(float));
这有帮助吗?请注意分配矩阵的第二种方式。
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
size_t r = 0;
size_t c = 0;
int rows = 82;
int columns = 30;
float *matrix = malloc(rows * columns * sizeof(float));
for(r = 0; r < rows; r++) {
printf("%zu - ", r);
for(c = 0; c < columns; c++) {
printf("%zu|", c);
matrix[r + r*c] = 1.0;
}
printf("\n");
}
float **matrix2 = malloc(rows * sizeof(float*));
for(r = 0; r < rows; r++) {
matrix2[r] = malloc(columns * sizeof(float));
}
for(r = 0; r < rows; r++) {
printf("%zu - ", r);
for(c = 0; c < columns; c++) {
printf("%zu|", c);
matrix2[r][c] = 1.0;
}
printf("\n");
}
free(matrix);
for(r = 0; r < rows; r++) {
free(matrix2[r]);
}
free(matrix2);
return 0;
}
您可以在此处找到带有代码的基准...
https://github.com/harryjackson/doc/blob/master/c/cache_locality_2d_array_test.c
关于c - 难以在堆上创建连续的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36511278/