简体   繁体   English

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

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

I want to allocate memory for 3d array in c++ one by one like.. 我想逐个为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));
      }
   }
}

i have used this code but i am getting segmentation fault.. 我已经使用了这段代码,但我得到了分段错误..

Write

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

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

Or try something like the following 或尝试以下内容

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 ) );
    }
}

Calculate the total amount of memory needed first then allocate memory first for main array and the sub arrays as below. 首先计算所需的内存总量,然后首先为主阵列和子阵列分配内存,如下所示。 It won't cause segmentation fault. 它不会导致分段错误。 Even you can check the addresses also they are contiguous . 即使您可以检查地址也是连续的 Try below code it works fine for me: 尝试下面的代码它对我来说很好:

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");
                }
}

You've already allocated memory when you wrote 你写的时候已经分配了内存

slotstruct slot1[3][100][1500]

Did you mean to write following? 你的意思是写下面的吗?

slotstruct ***slot1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM