c - 难以在堆上创建连续的二维数组

标签 c arrays segmentation-fault malloc

我目前正在堆上实现一个 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/

相关文章:

c - 如何检查字符串是否没有任何字母数字字符?

c++ - 使用 OpenCV 从图像中提取数字

c - 结构段错误 : 11. 无法重新分配首先初始化为 null 的结构中的值

PHP - 使用 PDO 从列索引中获取字段名称

javascript - 有没有办法在javascript中复制对象数组?

c - 为什么 Valgrind 会清理我的输入文本文件?

c - 链表 : count=count->next gives segmentation fault

c - 我怎样才能在 FreeBSD 系统调用 openat 中获得绝对路径?

c - 模幂不适用于 C 中的大数

JavaScript。从关联数组中提取值