#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define Stack_Size 50
//栈顺序存储结构定义
typedef struct
{
int elem[Stack_Size];
int top;
}SeqStack;
//初始化
void InitStack(SeqStack *S)
{
S->top = -1;
}
//判断栈空
int IsEmpty(SeqStack *S)
{
return(S->top == -1 ? TRUE : FALSE);
}
//判断栈满
int IsFull(SeqStack* S)
{
return(S->top == Stack_Size - 1 ? TRUE : FALSE);
}
//进栈
int Push(SeqStack* S, int x)
{
if (S->top == Stack_Size - 1)return(FALSE);
S->top++;
S->elem[S->top] = x;
return(TRUE);
}
//出栈
int Pop(SeqStack* S, int* x)
{
if (S->top == -1)
return(FALSE);
else
{
*x = S->elem[S->top];
S->top--;
return(TRUE);
}
}
//取栈顶元素
int GetTop(SeqStack* S, int *x)
{
if (S->top == -1)
return(FALSE);
else
{
*x = S->elem[S->top];
return(TRUE);
}
}
//输出栈
void PrintStack(SeqStack* S)
{
int i;
printf("栈中元素为:");
for (i = 0;i <= S->top;i++)
{
printf("%d", S->elem[i]);
}
printf("\n");
}
int main()
{
SeqStack* S=NULL;
int x;
InitStack(S);
printf("请输出栈中元素:");
scanf("%d", &x);
Push(S, x);
printf("创造的栈为:");
PrintStack(S);
}

为什么没有运行结果?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
4条回答 默认 最新
- 技术专家团-小桥流水 2022-11-29 08:59关注
main函数中,S没有分配内存,有两种修改方法,一是声明一个SeqStack变量,让S指向该变量的地址。第二种方法是用malloc分配内存。
修改方法一:int main() { SeqStack st; //系统自动为st分配内存 SeqStack* S = &st; //S 指向st的地址 int x; InitStack(S); printf("请输出栈中元素:"); scanf("%d", &x); Push(S, x); printf("创造的栈为:"); PrintStack(S); }
修改方法二:
int main() { SeqStack* S = (SeqStack*)malloc(sizeof(SeqStack)); // 手动分配内存 int x; InitStack(S); printf("请输出栈中元素:"); scanf("%d", &x); Push(S, x); printf("创造的栈为:"); PrintStack(S); }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录