我想在 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/