1

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;
}
sunside
  • 8,069
  • 9
  • 51
  • 74
Win
  • 11
  • 1

1 Answers1

2

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);).

Community
  • 1
  • 1
sunside
  • 8,069
  • 9
  • 51
  • 74
  • `*stringLength` certianly should be `*(stringLength+1)`. Why suggest casting the result of `malloc()` (not needed) and multiplying by `sizeof(char)` which in 1? Alternate: `ver[0]->cityName = malloc(stringLength + 1);` – chux - Reinstate Monica Mar 09 '15 at 20:47
  • I am assuming `stringLength` to contain the terminator as per the example above, but you're certainly right about `sizeof(char)`; it's just a matter of personal taste to be explicit about what you want to achieve. The compiler is likely to optimize it away anyways. – sunside Mar 09 '15 at 20:54