typedef 指针使用 fgets 输入数据,但需要最后一个 fgets

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

我正在尝试将文件中的邮政编码读取到 Object * 数组中。 文件包括 123 无处不在 柯克兰 加州 99223

我的 .h 文件看起来像

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

我填充数组

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;

当它读取它时,当我尝试打印它时它最终看起来像这样

街道:99004 城市:99004 状态:99004 邮编:99201

不知道出了什么问题任何帮助将不胜感激!谢谢

strdup 将分配一个适当大小的缓冲区并复制字符串,例如

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

实际上,streetcitystate 都指向 line,每次调用 fgets 时都会被覆盖。