gpt4 book ai didi

c - C中的堆栈代码一运行就崩溃并停止工作

转载 作者:行者123 更新时间:2023-12-01 22:53:13 25 4
gpt4 key购买 nike

因此,我正在使用 C 语言编写标准堆栈程序,其中包含推送、弹出等功能。代码编译正常,但一旦我运行它,它就会崩溃并显示“已停止工作”消息。我正在 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)

关于c - C中的堆栈代码一运行就崩溃并停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51826528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com