I am trying to create a dynamic array of dynamic structs but I can't get it working properly. It prints all the info but it gives return error. If I comment the line containing:
printf(" m[%i][%i] ID: %i VALUE: %f\n", i, j, m[i]->id, m[i]->values[j]);
It compiles OK and returns 0. What am I doing wrong? I am just beginning learing C and in the process of dealing with pointers.
#include <stdio.h>
#include <stdlib.h>
typedef struct listDef{
int id;
float *values;
} ListSt;
int main()
{
int max_fil, fil, col;
max_fil = 4; /* Max 'ListSt' elements*/
fil=2; /* Rows */
col=4; /* Columns */
ListSt **m = NULL;
int count = 0;
int sizes[] = {4,6,8,10}; /* The sizes of each 4 elements to be created */
m = (ListSt **)malloc(sizeof(int*)*max_fil); /* Assign a memory address for accesing 'm' (ListSt) */
for(int i=0;i<fil;i++){
m[i]->values = (float *)malloc(sizeof(float)*sizes[i]);
m[i]->id = i;
printf("-----------\n");
printf("Element n.%i :\n\n", i);
for(int j=0;j<sizes[i];j++){
m[i]->values[j] = 0.1234*(i+1);
/* If I comment the next line, it compiles OK. */
printf(" m[%i][%i] ID: %i VALUE: %f\n", i, j, m[i]->id, m[i]->values[j]);
int testint;
float testfloat;
testint = m[i]->id;
testfloat = m[i]->values[j];
}
}
free(m);
return 0;
}