我想为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));
}
}
}我使用过这段代码,但我得到了分段错误..
发布于 2016-09-05 12:23:23
首先计算所需内存总量,然后为主数组和子数组分配内存,如下所示。不会造成分割错误。甚至您也可以检查地址,它们也是连续的。试试下面的代码,它对我来说很好:
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");
}
}发布于 2016-09-05 10:53:01
写
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 ) );
}
}发布于 2016-09-05 10:52:45
当你写到
slotstruct slot1[3][100][1500]你是想写跟帖吗?
slotstruct ***slot1https://stackoverflow.com/questions/39328990
复制相似问题