[英]how to allocate memory for 3D array using calloc in c++
我想逐个为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 ) );
}
}
首先计算所需的内存总量,然后首先为主阵列和子阵列分配内存,如下所示。 它不会导致分段错误。 即使您可以检查地址也是连续的 。 尝试下面的代码它对我来说很好:
typedef struct
{
int id;
int use;
}slotstruct;
main()
{
int i,j,k;
char row=2 ,col =3, var=3;
//char **a=(char**)malloc(col*sizeof(char*));
slotstruct*** a =(slotstruct***)calloc(col,sizeof(slotstruct*));
for(i=0;i<col;i++)
a[i]=(slotstruct**)calloc(row,sizeof(slotstruct*));
for(i=0;i<col;i++)
for(j=0;j<row;j++)
a[i][j]=(slotstruct*)calloc(var,sizeof(slotstruct*));
int cnt=0;
for( i=0;i<col;i++)
for( j=0;j<row;j++)
{
for(k=0;k<var;k++)
a[i][j][k].id=cnt++;
}
for(i=0;i<col;i++)
for(j=0;j<row;j++)
{
for(k=0;k<var;k++)
printf("%d ",a[i][j][k].id);
printf("%u ",&a[i][j][k]);
printf("\n");
}
}
你写的时候已经分配了内存
slotstruct slot1[3][100][1500]
你的意思是写下面的吗?
slotstruct ***slot1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.