gpt4 book ai didi

c - 我的程序给出了 Segmentation Fault 错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:52:27 24 4
gpt4 key购买 nike

我正在用 Dev C++ 编写一个单链表的 C 程序其代码如下:

#include<stdio.h>
typedef struct node
{
int data;
struct node *next;
}node;
node *insert(node*,int,int);
node *create(int);
node *del(node*,int);
int print(node*);
int main()
{
node *head;
int n,ch,n1,x,key,k;
head = NULL;
printf("\n Number of nodes:");
scanf("%d",&n);
while(1)
{
printf("\nYour choices are:");
printf("\n1) Create");
printf("\n2) Print");
printf("\n3) Insert");
printf("\n4) Delete");
printf("\n5) Reverse\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
head = create(n);
break;

case 2:
n1 = print(head);
break;

case 3:
printf("Enter the element to be inserted:");
scanf("%d",&x);
printf("Enter the position where it is to be inserted:");
scanf("%d",&key);
head = insert(head,x,key);
break;

case 4:
printf("Enter the element to be deleted:");
scanf("%d",&k);
head = del(head,k);
break;

case 5:
break;

default:
exit(0);
break;
}
}
return(0);
}
node *create(int n)
{
node *head,*p;
int i;
printf("Enter %d data fields",n);
head = (node*)malloc(sizeof(node));
head->next = NULL;
scanf("%d",&(head->data));
p=head;

for(i=1;i<n;i++)
{
p->next = (node*)malloc(sizeof(node));
p=p->next;
scanf("%d",&(p->data));
p->next=NULL;
}
printf("Linked list created.");
return(head);
}
int print(node *p)
{

while(p!=NULL)
{
printf("%d-->",p->data);
p=p->next;
}
printf("NULL");
return(0);
}
node *insert(node *head,int x,int key)
{
node *p,*q;
p = (node*)malloc(sizeof(node));
p->data = x;
if(key==-1)
{
p->next = head;
head=p;
}
else
{
q = head;
while(key != q ->data && q!=NULL)
q=q->next;
if(q!=NULL)
{
p->next = q->next;
q->next = p;
}
}
printf("Element Inserted.");
return(head);
}
node *del(node *head,int x)
{
node *p,*q;
if(x == head->data)
{
p = head;
head = head->next;
free(p);
}
else
{
while(x != (p->next)->data && p->next != NULL)
p=p->next;
if(p->next != NULL)
{
q = p->next;
p->next = (p->next)->next;
free(q);
}
}
return(head);
}

一切顺利,但是当我尝试删除一个节点时,控制台崩溃了,当我调试它时它显示“访问冲突错误:段错误”我的程序出了什么问题。

最佳答案

指针 p 在 del(..) 的 else block 之前没有被初始化。

p 是空指针时,您不能访问 p->next

关于c - 我的程序给出了 Segmentation Fault 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19164155/

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