c - 为什么我在这个 STACK 程序中得到这个数字而不是值?

标签 c stack undefined-behavior

在这个用 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/

相关文章:

c - i++, i=i+1 和 i+=1 哪个更快?

c - 使用unput错误

c++ - 在头文件重新定义错误中包含 .cpp - 实现通用堆栈

c - c 中带符号整数的模算术未定义行为?

c中计算字符串中不同符号的个数

c - 如何定期自动调用函数?

c# - F# NativePtr.stackalloc 比 C# stackalloc 慢 - 包含反编译代码

html堆栈顺序

c - 链表实现中的运行时错误

c - (在哪里)clang 是否记录了实现定义的行为?