首页 > 解决方案 > 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循环中,但我不确定。想对这个问题发表一些意见。

标签: cpointersstack

解决方案


  st *s;

您没有分配内存*s,将其更改为

  st *s = malloc(sizeof(*s));

或者

  st s;
  createemptyStack(&s)

推荐阅读