堆栈总是空的

Stack is always empty

即使我在推东西的时候,keni(S) 总是returns -1。就像我可以推,但是当我试图弹出时,它总是 returns “堆栈是空的!”。感谢您的宝贵时间!

#include <stdio.h>
#define N 5

typedef struct{
    float s[N];
    int top;
}Stiva;

int keni(Stiva);
void dimiourgia(Stiva*);
void push(Stiva *, float);
float pop(Stiva *);

void dimiourgia(Stiva *St)
{
    St->top = -1;
}

int keni(Stiva S)
{
    if (S.top == -1)
        return -1;
    else 
        return 0;
}

void push(Stiva *St, float a)
{
    if (St->top == N-1) {
        printf("\n\nStack Overflow");
        return;
    }
    else {
        St->top ++;
        St->s[St->top] = a;
    }
}

float pop(Stiva *St)
{
    float c;

    c = St->s[St->top];
    St -> top--;

    return c;
}

int main()
{
    Stiva S;
    float x;
    int epil;

    dimiourgia(&S);
    do{
        do{
            printf("\n\n1.Push 2.Pop 3.End\n");
            scanf("%d", &epil);
        }while (epil<1 || epil>3);
        switch (epil) {
            case 1: if (S.top == N-1)
                        printf("\n\nStack is empty!\n\n");
                    else {
                        printf("\nPick a num\n\n");
                        scanf("%f", &x);
                        push(&S, x);
                    }
            case 2: if (keni(S) == -1)
                        printf("\n\nStack is empty!\n\n");
                    else {
                        x = pop(&S);
                        printf("\n\n==> %10.2f", x);
                    }
        }
    } while(epil!=3);
    return 0;
}

总之这是解决方法

    switch (epil) {
        case 1: if (S.top == N-1)
                    printf("\n\nStack is empty!\n\n");
                else {
                    printf("\nPick a num\n\n");
                    scanf("%f", &x);
                    push(&S, x);
                }
                break; <<<<==============================
        case 2: if (keni(S) == -1)
                    printf("\n\nStack is empty!\n\n");
                else {
                    x = pop(&S);
                    printf("\n\n==> %10.2f", x);
                }
    }

在你按下一个数字后,你会立即再次弹出它

1.Push 2.Pop 3.End
1

Pick a num

42


1.Push 2.Pop 3.End
1

Pick a num

44


1.Push 2.Pop 3.End
2


==>      44.00

1.Push 2.Pop 3.End
2


==>      42.00

1.Push 2.Pop 3.End
2


Stack is empty!



1.Push 2.Pop 3.End

通过在调用 push 的地方设置一个断点并简单地单步执行并观察代码来找到