如何在 C++ 中使用 calloc 为 3D 数组分配内存
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[3][100][1500]
您是要写以下内容吗?
slotstruct ***slot1
写
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");
}
}
我想在 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[3][100][1500]
您是要写以下内容吗?
slotstruct ***slot1
写
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");
}
}