在shareRecord while循环中使用ptr!= NULL时出现分段错误,但是当我使用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;
}
答案 0 :(得分:1)
当ptr != NULL
导致错误时,循环将中断。这意味着当它中断时,ptr IS NULL
。所以下一行,
if(ptr->next == NULL && flag == 0){
您正在尝试使用属性NULL
,该属性应该会导致错误。