Reputation: 11
I want to ultimately insert strings from a file into elements in structs and can't get it right. Can you see what is wrong here?
int main()
{
FILE *fp;
char file_name[10] = "map7.map";
fp = fopen(file_name,"r");
int a = 1;
int *pnumberOfRows = &a;
fscanf(fp,"%d",pnumberOfRows);
typedef struct {
bool visited;
char *cityName;
} map;
map *ver = malloc(sizeof(map)*2*(*pnumberOfRows));
fscanf(fp,"%s",ver[1].cityName);
printf("%s",ver[1].cityName);
return 0;
}
Upvotes: 1
Views: 98
Reputation: 8259
It seems like you're simply missing to allocate space for the char *cityName
fields, which makes you fscanf
onto an unallocated pointer. You could either provide a fixed-with field, e.g.
typedef struct {
bool visited;
char cityName[81];
} map;
for a maximum length of 80 characters (i.e. excluding \0
) or determine the length of the city names in the file beforehand and then allocating memory to the field using
ver[0]->cityName = (char*)malloc(sizeof(char)*(stringLength+1));
Note that sizeof(char) == 1
, so feel free to leave it away, but see the answers here for more information. I left it here for the sake of being expressive about what you want to achieve.
Also, don't forget to free
the memory you malloc
'd at the end and also close the file descriptor after you're done (i.e. fclose(fp);
).
Upvotes: 1