typedef struct school_ {
char *name;
char *state;
} School;
Above is the struct format I am required to use to store data from a file in the format
name, state
name2, state2
Below I was given a declaration of an array of pointers and the second line is how the function is called.
School *TOP100[school_size];
input_schools(school_info,TOP100,school_size);
In my function I need to store a dynamic string as the name for each of 100 schools.
I've written the following, however have gotten a seg fault. How can I change my function without changing the code above?
void input_schools(FILE *IN, School **Sch, int k) {
printf("in input_schools() ... \n\n\n");
int i, j = 0;
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';
}
return;
}
While this code compiles it returns a seg fault.