C检查数组堆栈是否为空问题

C check if array stack its empty or not problem

我创建数组堆栈和 2 个函数。函数push向堆栈添加东西,函数isempty检查堆栈是否为空但它不起作用,所以错误在哪里。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

#define MAX 10

struct stack
{
    int items[MAX];
    int top;
};

typedef struct stack st;

int isempty(st *s)
{
    if (s->top==-1)
    {
        printf("it's empty");
    }
    else
    {
        printf("it's not empty");
    }
}

void push(st *s)
{
    int newitem;
    printf("Enter item: ");
    scanf("%d",&newitem);
    s->top++;
    s->items[s->top]=newitem;
}

int main()
{
    st *s;
    push(s);
    isempty(s);
    return 0;
}

函数 isempty 具有非空 return 类型。所以它必须return一个值。例如

int isempty(st *s)
{
    if (s->top==-1)
    {
        printf("it's empty");
    }
    else
    {
        printf("it's not empty");
    }

    return s->top==-1;
}

第二个问题是你没有初始化指向结构对象的指针

st *s;

不需要声明指针。你可以写

st s = { { 0 }, -1 };

并调用

等函数
push( &s );
isempty( &s );

你需要一个初始化函数来初始化s->top

另一方面,您定义了 *s 但您没有为堆栈分配内存,您只分配了一个指向未初始化位置的指针。