C 新来的程序员,这个堆栈程序怎么了?
当我执行它时,函数不工作为什么C 新来的程序员,这个堆栈程序怎么了?,c,struct,C,Struct,当我执行它时,函数不工作为什么 #include<stdio.h> struct stack{ int x[10]; int last; }; void init(struct stack *s) { s->last=0; } void insert(struct stack *s) { int a; while(a!=0) { int i; printf("Ente
#include<stdio.h>
struct stack{
int x[10];
int last;
};
void init(struct stack *s)
{
s->last=0;
}
void insert(struct stack *s)
{
int a;
while(a!=0)
{
int i;
printf("Enter the value\n");
scanf("%d",&i);
s->last++;
s->x[s->last]=i;
printf("%d",s->x[s->last]);
printf("enter 1 to continue 0 to exit\n");
scanf("%d",&a);
}
}
int main()
{
struct stack s;
int y,z;
printf("Trying out stacks\n");
printf("\n______________\n");
init(s);
insert(s);
return 0;
}
#包括
结构堆栈{
int x[10];
int last;
};
void init(结构堆栈*s)
{
s->last=0;
}
空插入(结构堆栈*s)
{
INTA;
while(a!=0)
{
int i;
printf(“输入值”);
scanf(“%d”、&i);
s->last++;
s->x[s->last]=i;
printf(“%d”,s->x[s->last]);
printf(“输入1以继续0以退出\n”);
scanf(“%d”和“&a”);
}
}
int main()
{
结构栈;
int y,z;
printf(“尝试堆栈\n”);
printf(“\n\uuuuuuuuuuuuuuuuuuuuuuu\n”);
初始值(s);
插入(s);
返回0;
}
在函数insert()
中,您声明
int a;
然后在不初始化a
的情况下执行以下操作
while(a!=0)
我会给你的
以下行可能导致缓冲区溢出
s->last++;
s->x[s->last]=i; // no restriction applied on last
last
可以超过9
,这会导致缓冲区溢出,如x[10]
为什么您认为此代码不起作用?你对此有什么指示?描述问题。inta代码>-->inta=1代码>,s->last=0代码>-->s->last=-1代码>,init(s)代码>-->初始化(&s)代码>,插入代码>-->插入(&s)代码>