c - C 中的堆栈代码在运行后立即崩溃并停止工作
问题描述
所以,我在 C 中使用 push、pop 等编写标准堆栈程序。代码编译得很好,但是一旦我运行它,它就会崩溃并显示“停止工作”消息。我正在开发 Windows 系统上的 Dev C++ 应用程序。代码如下:
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct stack {
int items[MAX];
int top;
};
typedef struct stack st;
void createemptyStack(st *s) {
s->top = -1;
}
int isEmpty(st *s) {
if (s->top == -1)
return 1;
else
return 0;
}
int isFull(st *s) {
if (s->top == MAX - 1)
return 1;
else
return 0;
}
int push(st *s) {
int newitem;
printf("Enter the value you want to push");
scanf("%d", &newitem);
if (isFull(s)) {
printf("Stack is full");
} else {
s->top++;
s->items[s->top] = newitem;
}
}
void pop(st *s) {
if (isEmpty(s)) {
printf("Stack is empty");
} else {
printf("Items popped %d", s->items[s->top]);
s->top--;
}
}
int main() {
int ch;
int loop = 1;
st *s;
createemptyStack(s);
do {
printf("\n ***STACK OPERATIONS");
printf("\n 1. PUSH");
printf("\n 2. POP");
printf("\n 3. EXIT");
printf("\n ***************");
printf("\n Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
push(s);
break;
case 2:
pop(s);
break;
case 3:
printf("Visit again");
loop = 0;
exit(0);
default:
printf("Invalid choice");
}
} while(loop);
getch();
}
如果你能在这件事上帮助我,那对我真的很有帮助。我认为问题可能存在于do / while
循环中,但我不确定。想对这个问题发表一些意见。
解决方案
st *s;
您没有分配内存*s
,将其更改为
st *s = malloc(sizeof(*s));
或者
st s;
createemptyStack(&s)
推荐阅读
- python - 检查交易组之间的值是否发生变化
- java - 验证对象不接受数据类型的 SPRING 函数
- angular - 未定义 fetchCompletion 中的错误 - Angular 10 Visual Studio 代码
- ios - 将按钮添加到显示另一个模态视图控制器的自定义单元格
- python - 无法访问 top.api 中的 Aliexpress 功能
- react-native - 使用 Horizontal={true} 左右滚动 React Native Flatlist
- c - 在C中将负十进制转换为二进制补码
- c++ - 为什么 std::tuple 调用运算符 <=> 两次?
- javascript - api 在 beforeunload 事件中停留在挂起状态
- json - 如何在 Json Schema 中有条件地添加必填字段,以对其兄弟 json 元素的 json 元素宽度子元素进行露营?