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

时间:2015-03-12 02:48:55

标签: c malloc typedef fgets calloc

我试图将邮件中的邮政编码读入Object *数组。 文件包括 123无处不在 柯克兰 CA 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

不知道什么是错误任何帮助将不胜感激!感谢

1 个答案:

答案 0 :(得分:1)

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

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

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