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

how to allocate memory for 3D array using calloc in c++

本文关键字:3D 数组 分配 内存 calloc c++      更新时间:2023-10-16

我想在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));
      }
   }
}

我已经使用了这个代码,但我得到分割错误。

Write

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