Search code examples
cmalloctypedeffgetscalloc

typedef pointer using fgets to input data, but takes last fgets


I'm trying to read postal codes from a file into an Object * array. file includes 123 Anywhere kirkland CA 99223

my .h file looks like

 typedef struct
{
    char *street;
    char *city;
    char *state;
    int zip;
}Address;

my filling the array

Address * fillArray(int * total, FILE * fin)
{Address * array = NULL; int n =0; char line[256];int count=0;
   while (fgets(line,256,fin)!=NULL) 
   {count++;}
   count = count/4;
   *total = count;//total of arrays
   rewind(fin);//start of file
   //printf("total : %d",*total);
   array = (Address *)malloc(sizeof(Address*)*count);
   for(n=0;n<count;n++)
   {
      array[n] = *((Address *) calloc(1,sizeof(Address)));
   }
   for(n=0;n<*total;n++)
   {
      fgets(line,sizeof(line),fin);
      array[n].street=line;
      printf("%s",array[n].street);
      fgets(line,sizeof(line),fin);
      array[n].city = line;
      printf("%s",array[n].city);
      fgets(line,sizeof(line),fin);
      array[n].state = line;
      fgets(line,sizeof(line),fin);
      array[n].zip=atoi(line);
   }



   fclose(fin);
   return array;

when it reads it it'll end up looking like this when i try to print it

street: 99004 city: 99004 state: 99004 zip: 99201

no idea whats going wrong any help would be greatly appreciated! thanks


Solution

  • strdup will allocate a properly sized buffer and make a copy of the string, e.g.

    array[n].street = strdup( line );
    

    As it is, street, city and state all point to line, which gets overwritten every time you call fgets.