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