空条件不显示输出

问题描述 投票:0回答:1
struct node* position(int key)
{
    struct node *p1=head;
    while(p1->info!=key&&p1!=NULL)
    {p1=p1->link;
    }
    if(p1==NULL)
        printf("Insertion not possible");
    return p1;
}


insertafter(int item)
{
 struct node *new=(struct node*)malloc(sizeof(struct node));
 struct node *p2=position(item);
int ele;
printf("Enter element to be inserted ");
scanf("%d",&ele);
if(p2==NULL)
    printf("Insertion not possible");
else
{

    new->info=ele;
    new->link=p2->link;
    p2->link=new;
    
}  

}

因此,除了当我进行空条件检查时,其他一切都工作正常。它会在所需元素之后正确插入,但如果我给出链接列表中不存在的元素,它应该返回不可能插入,因为该元素是未找到(空条件),但它显示分段错误。

c function linked-list null segmentation-fault
1个回答
0
投票

分段错误是由于位置函数的 while 循环中的条件顺序造成的。您首先检查

p1->info != key
,然后检查
p1 != NULL
。如果
p1
NULL
,尝试访问
p1->info
将导致分段错误。要解决此问题,您应该在尝试访问其成员之前首先检查
p1
是否是
NULL

struct node* position(int key)
{
    struct node *p1 = head;
    while(p1 != NULL && p1->info != key)
    {
        p1 = p1->link;
    }
    if(p1 == NULL)
        printf("Insertion not possible\n");
    return p1;
}
© www.soinside.com 2019 - 2024. All rights reserved.