循环条件为ptr时的C - 分段错误!= NULL [关闭]

问题描述 投票:-2回答:1

我在循环中在shareRecord中使用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;
}
c pointers segmentation-fault
1个回答
1
投票

ptr != NULL导致错误时,循环将中断。这意味着当它破裂时,ptr IS NULL。那么下一行,

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

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

© www.soinside.com 2019 - 2024. All rights reserved.