This is probably a basic question but I want to allocate the memory for 3 dimensional array of a struct. I'm trying to read doubles from a file and want to store in struct. The first line is block number (not relevant here as it'll be 1 always), second line denotes the number of grid points in X, Y and Z coordinate respectively. In this case 10 points in X, 5 in Y and 1 in Z direction. And from third line, are the X,Y,Z coordinates of each points which are the doubles I would like to read. First there are all X components (i.e. 10*5*1 x coordinates, then similarly Y and Z). The file format is like this:
1
10 5 1
0.000000e+00 1.111111e+00 2.222222e+00 3.333333e+00
4.444445e+00 5.555555e+00 6.666667e+00 7.777778e+00
8.888889e+00 1.000000e+01 0.000000e+00 1.111111e+00
2.222222e+00 3.333333e+00 4.444445e+00 5.555555e+00
6.666667e+00 7.777778e+00 8.888889e+00 1.000000e+01
0.000000e+00 1.111111e+00 2.222222e+00 3.333333e+00
4.444445e+00 5.555555e+00 6.666667e+00 7.777778e+00
8.888889e+00 1.000000e+01 0.000000e+00 1.111111e+00
2.222222e+00 3.333333e+00 4.444445e+00 5.555555e+00
6.666667e+00 7.777778e+00 8.888889e+00 1.000000e+01
0.000000e+00 1.111111e+00 2.222222e+00 3.333333e+00
4.444445e+00 5.555555e+00 6.666667e+00 7.777778e+00
8.888889e+00 1.000000e+01...and so on...
I can read the first 4 integers and hence I know the number of points I wish to store data for. Then I'm using malloc function to allocate the memory and store the data in the variables. When I execute the program, it reads the integers but fails to read the doubles. What is the mistake I'm making?
Here's my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
double x,y,z;
}Mesh;
int main(void)
{
int nblocks, IMAX, JMAX, KMAX;
Mesh ***grid;
FILE *mesh = fopen("test.x","r");
fscanf(mesh,"%i %i %i %i",&nblocks,&IMAX,&JMAX,&KMAX);
printf("%i %i %i %i\n",nblocks,IMAX,JMAX,KMAX);
grid = malloc(sizeof(Mesh)*nblocks*IMAX*JMAX*KMAX);
fscanf(mesh,"%lf",&grid[0][0][0].x);
printf("%lf\n",grid[0][0][0].x);
fclose(mesh);
return 0;
}
The program doesn't give any error while compiling but it does't read/write the variable I stored in the x variable of the struct. (If this works, I can put it in loop for reading all values which I've not done here.)
If I define Mesh grid[IMAX][JMAX][KMAX]
after I read in IMAX,JMAX,KMAX
, I get correct output. But wanted to know how pointer way of doing works.
Thank you, Pranav