我在共享记录中使用 ptr 时遇到分段错误 != 空 而循环,但当我使用 ptr->next != NULL 时它似乎有效。
因此,当我使用 ptr->next != NULL 并取消注释 shareRecord 中的行时,代码有效。但是为什么它不能使用 ptr != NULL 工作。
请让我知道问题是什么。
struct data *shareRecord(struct data *head, struct data *fileline){
struct data *ptr;
ptr = head;
int flag = 0;
while(ptr != NULL){
if((strcmp(ptr->symbol, fileline->symbol) == 0) && (strcmp(ptr->type, fileline->type) == 0 )&& (ptr->time == fileline->time)){
flag = 1;
break;
}
ptr = ptr->next;
}
//if((strcmp(ptr->symbol, fileline->symbol) == 0) && (strcmp(ptr->type, fileline->type) == 0 )&& (ptr->time == fileline->time)){
//flag = 1;
//}
if(ptr->next == NULL && flag == 0){
return NULL;
}
else
return ptr;
}
struct data *create_data(struct data *head, struct data *fileline){
struct data *newdata, *ptr1, *ptr2;
struct price *newprice, *priceptr1;
newprice = (struct price *)malloc(sizeof(struct price *));
newprice->amt = fileline->price->amt;
newprice->next = NULL;
if(head == NULL){
newdata = (struct data *)malloc(sizeof(struct data));
newdata->time = fileline->time;
strcpy(newdata->symbol, fileline->symbol);
strcpy(newdata->type, fileline->type);
newdata->price = newprice;
newdata->next = NULL;
head = newdata;
}
else{
ptr1 = head;
ptr2 = head;
if((ptr1 = shareRecord(head, fileline)) != NULL){
priceptr1 = ptr1->price;
while(priceptr1->next != NULL){
priceptr1 = priceptr1->next;
}
priceptr1->next = newprice;
}
else{
while(ptr2->next != NULL){
ptr2 = ptr2->next;
}
newdata = (struct data *)malloc(sizeof(struct data));
newdata->time = fileline->time;
strcpy(newdata->symbol, fileline->symbol);
strcpy(newdata->type, fileline->type);
newdata->price = newprice;
newdata->next = NULL;
ptr2->next = newdata;
}
}
return head;
}
当ptr != NULL
将导致 false 时,循环将中断。这意味着当它破裂时,ptrIS NULL
。所以下一行,
if(ptr->next == NULL && flag == 0){
您正在尝试使用NULL
的属性,这应该会导致错误。