貌似溢出了 ,请问如何解决?

下面是代码
子函数visit中貌似有错
编译时能通过
但运行时会出错,要我调试
但我找不出到底是什么错误

#include <stdio.h>

typedef struct node
{
int date;
struct node *next;
}lstack;

void init(lstack *s)
{
s = (lstack *)malloc(sizeof(lstack));
s->next = NULL;
}

int push(lstack *s,int e)
{
lstack *p;
p = (lstack *)malloc(sizeof(lstack));
p->date = e;
p->next = s->next;
s->next = p;
return 1;
}

int pop(lstack *s)
{
lstack *p;
int e;
if(s->next == NULL)
{
printf("栈已空!");
return 0;
}
p = s->next;
e = p->date;
s->next = p->next;
printf("出战成功!\n");
free(p);
return 1;
}

int get(lstack *s)
{
int e;
if(s->next == NULL)
{
printf("栈已空!");
return 0;
}
e = s->next->date;
return e;
}

void visit(lstack *s)
{
lstack *p = s->next;
while(p != NULL)
{
printf("%d\n",p->date);
p = p->next;
}
}

int main()
{
int e = 0;
lstack s;
init(&s);
push(&s,1);
push(&s,2);
push(&s,3);
push(&s,4);
e = get(&s);
printf("栈顶元素为:%d\n",e);
pop(&s);
e = get(&s);
printf("栈顶元素为:%d\n",e);
visit(&s);
}

阿晨1998
浏览 164回答 2
2回答

蝴蝶不菲

#include <stdio.h>#include <stdlib.h>typedef struct node{int date;struct node *next;}lstack;void init(lstack *s){s->date = 0;s->next = NULL;}int push(lstack *s,int e){lstack *p;p = (lstack *)malloc(sizeof(lstack));p->date = e;p->next = s->next;s->next = p;return 1;}int pop(lstack *s){lstack *p;int e;if(s->next == NULL){printf("栈已空!");return 0;}p = s->next;e = p->date;s->next = p->next;printf("出战成功!\n");free(p);return 1;}int get(lstack *s){int e;if(s->next == NULL){printf("栈已空!");return 0;}e = s->next->date;return e;}void visit(lstack *s){lstack *p = s->next;while(p != NULL){printf("%d\n",p->date);p = p->next;}}int main(){int e = 0;lstack s;init(&s);push(&s,1);push(&s,2);push(&s,3);push(&s,4);e = get(&s);printf("栈顶元素为:%d\n",e);pop(&s);e = get(&s);printf("栈顶元素为:%d\n",e);visit(&s);}

MM们

不用init()把lstack s;init(&s);两句换成lstack s = {0,NULL};就没问题调试知init()函数返回后结构体中s.next不为空导致visit()溢出
打开App,查看更多内容
随时随地看视频慕课网APP