C-程序中没有输出
我做了一个堆栈,我正在使用 isEmpty 函数,但没有输出。我使用gcc命令和代码运行器扩展手动调整。这是代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack
{
int top;
int size;
int *arr;
} Stack;
int isEmpty(Stack *st)
{
if (st->top == -1)
{
return 1;
}
else
{
return -1;
}
}
int main()
{
Stack *st;
st->top = -1;
st->size = 10;
st->arr = (int *)malloc(st->size * sizeof(int));
int i = isEmpty(st);
if (i == 1)
{
printf("The stack is emptyn");
}
else
{
printf("The stack is not emptyn");
}
return 0;
}
该文件名为 Stack.c。还有一件事是基本的 hello world 程序运行良好
回答
Stack *st;
st->top = -1;
您通过访问未初始化的指针调用了未定义的行为st->top = -1;。
您应该st先初始化:
Stack *st = malloc(sizeof(Stack));