gpt4 book ai didi

C - 当循环条件为 ptr != NULL 时出现段错误

转载 作者:行者123 更新时间:2023-11-30 20:19:01 25 4
gpt4 key购买 nike

在 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;
}

最佳答案

ptr != NULL 结果为 false 时,循环将中断。这意味着当它中断时, ptr IS NULL 。所以下一行,

if(ptr->next == NULL && flag == 0){

您正在尝试使用 NULL 属性,这应该会导致错误。

关于C - 当循环条件为 ptr != NULL 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52137744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com