I am not understanding whats erroneous in the program. I am defining a pointer to an array of structures. Malloc'ed enough memory for it. Initialized the array elements. Then used fwrite to write the array on to a binary file. Then attempting to read the same, back into another pointer to a similar array, which has enough memory malloc'ed to it.
#include<stdio.h>
typedef struct ss{
int *p;
char c;
double d;
char g;
float f;
} dd;
main(){
dd (*tt)[5];
int i=0,a[5]={4,1,6,9,3};
tt=malloc(sizeof(struct ss[5]));
for(i=0;i<5;i++){
tt[i]->p=malloc(sizeof(int));
tt[i]->p=&a[i];
tt[i]->c=(char)('a'+i);
tt[i]->d=(double)(5.234234+i);
tt[i]->g=(char)('A'+i);
tt[i]->f=(float)(15.234234+i);
}
FILE *F;
F=fopen("myfile","w+b");
size_t l;
l=fwrite(tt,sizeof(*tt),1,F);
fseek(F,0,SEEK_SET);
//printf("sizeof(dd)=%d sizeof(*tt) =%d bytes written %d\n",sizeof(dd),sizeof(*tt),l);
dd (*xx)[5];
xx=malloc(sizeof(struct ss[5]));
l=fread(xx,sizeof(*xx),1,F);
for(i=0;i<5;i++){
printf("%d, %c,%f,%c,%f\n",*(xx[i]->p),xx[i]->c,xx[i]->d,xx[i]->g,xx[i]->f);
}
printf("Date Read %d \n",l);
for(i=0;i<5;i++){
free(xx[i]->p);
}
free(xx);
free(tt);
fclose(F);
remove("myfile");
}
Output:
4,a,5.234234,A,15.234234
Segmentation fault