Im currently working on a problem to store data from an input file into a struct of the following format:
typedef struct school_{
char *name;
char *state;
}School;
Im reading from an input file of the format :
name1, state1
name2, state2
And I would like to store the data dynamically for each school in a struct via pointers as the length of the name is unknown. k is the number of lines in the file. So far this is what I have:
void input_schools(FILE *IN, School **Sch, int k) {
int i, j;
char ch;
for (i=0; i<k; i++)
{ fscanf(IN, "%c", &ch);
Sch[i].name = (char *)malloc(sizeof (char));
j = 0;
Sch[i].name[j] = ch;
while(ch != '-') {
fscanf(IN, "%c", &ch);
j++;
Sch[i].name = (char *) realloc(Sch[i].name, sizeof(char)*(j+1));
Sch[i].name[j] = ch;
}
}
Sch[i].name[j-1] = '\0';
However I am receiving a seg fault which I'm assuming is from the way I'm trying to store "ch" when writing "Sch[i].name[j]" I have also tried Sch[i]->name[j] and been unsuccessful. I would appreciate any help in knowing the correct way to write the address to store the data?
I call the function using : input_schools(school_info,TOP100,school_size); where school info is the input file School *TOP100[school_size]; is top100 and school_size is the number of lines in the file