在这个用 C 语言实现的堆栈程序中,当我打印 pop() 的值时,为什么我得到的是那个数字?它应该打印“4”,但我却得到了一个像数字一样的地址。这可能是什么问题?
#define MAX 5
typedef struct stack{
int data[MAX];
int top;
}stack;
int empty(stack *s){
if(s->top==-1)
return 1;
return 0;
}
int pop(stack *s){
int x;
x = s->data[s->top];
s->top = s->top -1;
return x;
}
void display(stack *s){
while(!(empty(&s)) && (s->top)!=-1){
printf("%d\n",s->data[s->top]);
s->top=s->top-1;
}
}
int main()
{
stack s;
init(&s);
push(&s,2);
push(&s,3);
push(&s,4);
display(&s);
printf("Popped element is: ");
printf("%d",pop(&s));
return 0;
}
输出:
4
3
2
Popped element is: 4200976
Process returned 0 (0x0) execution time : 0.019 s
Press any key to continue.
最佳答案
在显示功能之后,您的顶部将始终具有 -1 的值。 使用 pop 函数时,它将返回数组中的第 -1 个元素。 这是未定义的行为,因此返回的 x 可以是任何东西。
关于c - 为什么我在这个 STACK 程序中得到这个数字而不是值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47633589/