do while 的奇怪行为

Strange behaviour of do while

我正在尝试实现一个堆栈。我想到了这个。除了尝试推送时,所有其他功能都按预期工作。当我尝试按 4 时,发生了一些奇怪的事情。

#include <stdio.h>
#include <stdlib.h>
#define MAX 10

typedef struct
{
    int a[MAX];
    int top;
}stack;

void init(stack *p)
{
    p->top=-1;
}

int full(stack *p)
{
    if(p->top==MAX)
        return 1;
    else
        return 0;
}

int empty(stack *p)
{
    if(p->top==-1)
    {
        init(p);
        return 1;
    }
    else
        return 0;
}

void display(stack *p)
{
    if(!empty(p))
    {
        printf("Stack is::\n");
        for(int i=0;i<=p->top;++i)
            printf("%d\t",p->a[i]);
        printf("\n");
    }
    else
    {
        printf("Stack is empty.\n");
        init(p);
    }
}

void push(stack *p, int x)
{
    if(!full(p)) /*full() returns 1 is top==max, 0 otherwise*/
    {
        p->a[p->top++]=x;
        printf("%d pushed.\n",x);
    }
    else
        printf("Stack is full.\n");
}

void pop(stack *p)
{
    if(!empty(p))
        printf("%d popped.\n",p->a[p->top--]);
    else
    {
        printf("Stack is empty.\n");
        init(p);
    }
}

int main()
{
    stack p;
    int ch,x;
    printf("Hello world!\n");
    init(&p);
    printf("*****MENU*****\n");
    do{
        printf("1.Push\n2.Pop\n3.Display\n4.Exit\n");
        printf("Enter your choice:: ");
        scanf("%d",&ch);
        switch(ch)
        {
            case 1:
                printf("Enter element to push:: ");
                scanf("%d",&x);
                push(&p,x);
                break;
            case 2:
                pop(&p);
                break;
            case 3:
                display(&p);
                break;
            case 4:
                exit(1);
        }
    }while(ch!=4);
    return 0;
}

程序终止。

我正在用 ch(=1) 而不是 x(=4) 测试 while 循环。那为什么会这样呢??

这个函数

void push(stack *p, int x)
{
    if(!full(p)) /*full() returns 1 is top==max, 0 otherwise*/
    {
        p->a[p->top++]=x;
        printf("%d pushed.\n",x);
    }
    else
        printf("Stack is full.\n");
}

错了。 top的初始值为-1所以在这个语句中

    p->a[p->top++]=x;

您正在尝试将值存储在索引等于 -1 的数组元素中。

因此程序有未定义的行为。

函数看起来像

void push( stack *p, int x )
{
    if ( !full( p ) ) /*full() returns 1 if top + 1 == max, 0 otherwise*/
    {
        p->a[++p->top]=x;
             ^^^^^^^^
        printf("%d pushed.\n",x);
    }
    else
    {
        printf("Stack is full.\n");
    }
}

考虑到在这种情况下,完整的函数应该看起来像

int full( const stack *p )
{
    return p->top + 1 == MAX;
           ^^^^^^^^^^
}

函数空也可以写得更简单

int empty( const stack *p )
{
    return p->top == -1;
}

并且堆栈通常以相对于输入元素的顺序相反的顺序打印

void display( const stack *p )
{
    if ( !empty( p ) )
    {
        printf( "Stack is::\n" );
        for ( int i = p->top; i != -1; --i )
            printf( "%d\t", p->a[i] );
        printf( "\n" );
    }
    else
    {
        printf( "Stack is empty.\n" );
    }
}