栈的压入程序,在赋值是出问题了

iceangellion 2002-05-01 12:06:41
下面是代码:
#include<stdio.h>
#include<iostream.h>
#define m0 4
typedef struct kk
{
int s[m0];
int top;
}stack;
void push(struct kk *st,int x)//x是插入到栈中的元素
{
if(st->top==0)printf("溢出\n");
else
{
st->top=st->top+1;
st->top=x;
}
}
void main()
{
struct kk *stack;
int x,i;
printf("初始化\n");
for(i=0;i<m0;i++)
//scanf("%d",&(stack->s[i]));//初始化栈
cin>>stack->s[i];
printf("cin the x\n");
scanf("%d",&x);
push(stack,x);
for(i=0;i<stack->top;i++)
printf("%d",stack->s[i]);
}
我想各位也不用我注解了,不过我的电脑在赋值是是非法操作,为什么????
...全文
41 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
晨星 2002-05-01
  • 打赏
  • 举报
回复
算了,给你个正确的吧。
#include<stdio.h>
#include<iostream.h>
#include<malloc.h>
#include<conio.h>

#define m0 4
typedef struct kk
{
int s[m0];
int top;
}stack;
void push(struct kk *st,int x)//x是插入到栈中的元素
{
if(st->top==m0 - 1)printf("溢出\n");
else
{
st->top=st->top+1;
st->s[st->top]=x;
}
}
void main()
{
struct kk *stack;
stack = (struct kk *) malloc(sizeof(struct kk));
stack->top = -1;
int x,i;
printf("初始化\n");
for(i=0;i<m0;i++)
//scanf("%d",&(stack->s[i]));//初始化栈
cin>>stack->s[i];
printf("cin the x\n");
scanf("%d",&x);
push(stack,x);
for(i=0;i<=stack->top;i++)
printf("%d",stack->s[i]);
getch();
}
晨星 2002-05-01
  • 打赏
  • 举报
回复
5。最后的输出应该是for(i=0;i<=stack->top;i++),因为你的top是先加后用的。
晨星 2002-05-01
  • 打赏
  • 举报
回复
问题太多了,我找出了以下几个:
1。push函数中的st->top=x;是否应改为st->s[top] = x;
2。main函数中的stack还没分配空间就往里边写数据。
3。push函数中判断溢出的条件应该是st->top==m0吧。
4。好像从来没有给stack的top字段赋过初值。
zhima2000 2002-05-01
  • 打赏
  • 举报
回复
up

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧