Strtok函数应该将字符串切成碎片。我用了#34; "最初是delim和" ,\ n"切割字符串。问题是当它从strtok函数获取NULL时,它继续分配并且不会中断循环。 因此它读取错误并为某些数据分配NULL。我认为问题是For循环内部的For循环,当它变为NULL时,它必须断开" token"但它没有。我怎么知道:我打印结构数据,它将NULL分配给最后一个字符串赋值,0分配给链接列表中最后一个元素的id。
所以很快它再工作一次,然后它应该是每次。虽然我试图将NULL指向当前它实际上并没有改变任何东西。 还读了一次。
typedef struct record_s {
int id;
char number[NAMELEN];
struct record_s *next;
} Record;
typedef struct person_s {
int id;
char name[NAMELEN];
double expenditure;
Record *numbers;
} Person;
typedef struct people_s {
Person data[MAXRECORD];
int size;
} People;
for(i=0;i<satir;i++){
current=(Record*)malloc(sizeof(Record));
people1.data[i].numbers=current;
head=people1.data[i].numbers;
fscanf(fp,"%d%s%s%lf",&people1.data[i].id,a,b,&people1.data[i].expenditure);
fgets (str, 60, fp);
token=strtok(str," ");
ztemp=0;
while (token != NULL)
{
ptr=(Record*)malloc(sizeof(Record));
strcpy(numbers[z],token);
strcpy(current->number,numbers[z]);
current->id=people1.data[i].id;
token = strtok (NULL, " ,\n");
current->next=ptr;
current=ptr;
z++;
ztemp++;
}
current=NULL;
people1.data[i].numbers=head;
test=head;
while(test!=NULL){
printf("%d is id, %s is supposedly the number\n",test->id,test->number);
test=test->next;
}
//printf("z is %d\n",ztemp);
strcat(a," ");
strcat(a,b);
strcpy(people1.data[i].name,a);
}
for(o=0;o<satir;o++){
x=0;
x=strcspn(numbers[o],"\n");
if(x!=0)
numbers[i][o]='\0';
}
people1.size=i;
fclose(fp);
print(people1);
return 0;
}
另外请指出,如果格式有任何问题而不是downvoting我会很快修复,我投票很少,谢谢。