请帮助我不知道错误在哪里。我遇到了段错误。我正在使用代码块作为 IDE。我是编程新手,这是我第一次尝试创建链表。 我想我的推送功能有问题,但我找不到它。
#include<stdio.h>
#include<stdlib.h>
typedef struct list
{
int val;
struct list* next;
} node;
int main()
{
node* top;
top = NULL;
int i;
int n,m;
while(1)
{
fflush(stdin);
printf("Please enter i\n");
scanf("%d", i);
switch(i)
{
case 1:
{
printf("\nenter val");
scanf("%d", &n);
top=push(n, top);
}
case 2:
{
m = pop(top);
printf("Deleted value is %d", m);
}
case 3:
{
return 0;
}
}
}
}
node* push(int a,node* s)
{
if(s==NULL)
{
s = malloc(sizeof(node));
s->val = a;
s->next = NULL;
return s;
}
else
{
node* temp;
temp = malloc(sizeof(node));
temp->val = a;
temp->next = s;
s = temp;
return s;
}
}
node* pop(node* s)
{
int x;
node* temp;
x = s->val;
printf("deleted value is %d", x);
temp = s->next;
s->next = NULL;
free(s);
s = temp;
return s;
}
最佳答案
您在当前代码中调用了 UB 2 次:
这就是出现段错误的原因。
解决这些问题后,您应该注意编译带有警告的代码将向您显示 m = pop(top);
行有问题,因为 m
是int
和 pop(top)
返回 node*
,所以我建议通过调整 pop
来解决这个问题函数,或 m
数据类型。
关于c - 无法创建堆栈。出现段错误。怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44133318/