c++ - 如何在 C++ 中使用 calloc 为 3D 数组分配内存

标签 c++ segmentation-fault dynamic-allocation calloc

我想在 C++ 中为 3d 数组分配内存,就像..

typedef struct {
int id;int use;
}slotstruct;
slotstruct slot1[3][100][1500];  // This should be 3d array
for(i=0;i<3;i++){
  for(j=0;j<100;j++){
     for(k=0;k<1500;k++){
         slot1[i][j][k] = (slotstruct *)calloc(1,sizeof(slotstruct));
      }
   }
}

我已经使用了这段代码,但我遇到了段错误..

最佳答案

slotstruct ( *slot1 )[100][1500];

slot1 = calloc( 1, 3 * sizeof( *slot1 ) ); 

或者试试下面的方法

slotstruct ***slot1;

slot1 = malloc( 3 * sizeof( slotstruct ** ) );

for ( int i = 0; i < 3; i++ )
{ 
    slot1[i] = malloc( 100 * sizeof( slotstruct * ) );
    for ( int j = 0; j < 100; j++ )
    {
        slot1[i][j] = calloc( 1, 1500 * sizeof( slotstruct ) );
    }
}

关于c++ - 如何在 C++ 中使用 calloc 为 3D 数组分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39328990/

相关文章:

c++ - 静态断言失败 : variant must have no reference alternative

c++ - Doxygen 中的 RTF 语法高亮显示

c++ - QtConcurrent blockingMappedReduced 与 MappedReduced

c - 动态分配的结构数组中的段错误,C

c++ - 在cocoa项目中使用boost库

c++ - 在 C++ 中捕获段错误

python - 如何从 Python 中的段错误中恢复?

c++ - 全局运算符 new 中的 std::ofstream

c++ - 动态分配类,有继承问题

c - BST 中的段错误