1

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

Bob
  • 43
  • 1
  • 1
  • 7
  • 1
    First, your allocation is wrong. Get rid of the calloc loop. All you need is `array = malloc(count * sizeof(*array));` or `array = calloc(count, sizeof(*array));` Second, you need to allocate and copy the strings. You could use strdup: `array[n].street = strdup(line);` – jschultz410 Mar 12 '15 at 03:37

1 Answers1

1

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.

user3386109
  • 34,287
  • 7
  • 49
  • 68