#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#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);
}
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);
}
InitStack就不对啊,指针都没分配空间你就赋值了,崩溃了
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!