I am experiencing trouble with memory allocation and de-allocation to the following C structure. I might be wrong, but I would like to know the correct procedure to do it.
//globally declared variables
int num_steps = 0;
int num_parts = 0;
//right now, I dont know how many timestep structures I will need and how many x,y & z would be needed in the structure. I would know that info in the run time. Later, in the run time, I would know for example:
num_steps = 10;
num_parts = 25;
//Then, in some function blaw_blaw():
void blaw_blaw(int num_steps, int num_parts)
timestep = (struct TIMESTEP *)malloc(num_steps*sizeof(struct TIMESTEP));
for(int i=0; i<num_steps; i++)
timestep[i].x = (float *)malloc(num_steps*sizeof(float));
timestep[i].y = (float *)malloc(num_steps*sizeof(float));
timestep[i].z = (float *)malloc(num_steps*sizeof(float));
for(int j=0; j<num_parts; j++)
for(i=0; i<num_steps; i++)
fscanf(fp3, "%s%s%s%s%s%s", s1, s2, s3); //obtained from some ascii file
timestep[i].x[j] = (float) atof(s1);
timestep[i].y[j] = (float) atof(s2);
timestep[i].z[j] = (float) atof(s3);
//I call this function at some place in my code. The above scheme of memory allocation and deallocation kind of worked for me once. However, later in my code when I had to re-use the variable with some more memory, the program crashed.
Question: IS THIS A CORRECT SCHEME OF MEMORY ALLOCATION AND DE-ALLOCATION TO C-STRUCTURES OF UNKNOWN NUMBER WITH ITS ARRAY MEMBERS OF UNKNOWN SIZE ? If NO, what is the correct way? I dont have any idea of linked lists, and I am out of time to learn the ABCDs of linked lists. Can some one really explain me how to allocate and de-allocate memory in the above structure ? I also dont know the x, y, z array sizes. Can some one please help me?