我在C中创建堆栈操作,但是当我尝试弹出最后一个元素时,它导致SEGMENTATION FAULT。
码
#include <stdio.h>
#include <stdlib.h>
typedef struct node1
{
int data;
struct node1 *link;
} node;
node *top,*header;
void push()
{
node *temp = (node *)malloc(sizeof(node));
printf("PUSH : ");
scanf("%d", &temp->data);
if (header == NULL)
{
top = temp;
header = temp;
temp->link = NULL;
}
else
{
temp->link = header;
header = temp;
top = temp;
}
}
void pop()
{
if (header == NULL)
printf("Stack Empty");
else
{
node *ptr = top;
top = header = top->link;
free(ptr);
}
}
void display()
{
node *ptr = header;
while (1)
{
if (ptr->link == NULL)
{
printf("%d", ptr->data);
break;
}
printf("%d", ptr->data);
ptr = ptr->link;
printf("->");
}
printf("\n\n");
}
int main()
{
printf("\nSTACK :\n\n");
while (1)
{
int choice;
printf("1.Push 2. Pop (Press ctrl + C to exit ): ");
scanf("%d", &choice);
switch (choice)
{
case 1:
push();
display();
break;
case 2:
pop();
display();
break;
default:
printf("Wrong Entry\n\n");
}
}
}
我知道一个类似的问题,在链表堆栈中的弹出功能导致分段错误-已问过C,但它对我没有帮助。为什么会发生此错误?问题是否与上述问题类似。
段错误是由于您的显示功能。在显示功能中,您可以进行检查,if (ptr->link == NULL)
但实际上应该进行检查if (ptr == NULL)
。如您所见,如果ptr
为NULL
,则引用ptr->link
将导致段错误。
在显示功能的while循环开始时,您可以尝试:if (ptr == NULL) break;
。更重要的是,请检查是否ptr
是NULL
由于while条件:
void display()
{
node *ptr = header;
while (ptr)
{
if (ptr->link == NULL)
{
printf("%d", ptr->data);
break;
}
printf("%d", ptr->data);
ptr = ptr->link;
printf("->");
}
printf("\n\n");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句