【问题标题】:Problem with pushing elements to the stack in c在c中将元素推入堆栈的问题
【发布时间】:2020-05-27 15:40:15
【问题描述】:

我在 C 中实现了一个堆栈,如下所示。并且该程序在三个推送中运行良好,但是当我尝试推送超过 3 个元素时,程序执行并且结果打印出来,但随后显示错误消息,指出 程序已停止工作
我的代码如下:

#include <stdio.h>
#include <stdlib.h>

#define MAX 50

//typedef char stackEntryType;
typedef enum{FALSE,TRUE} Boolean;

typedef struct stack{
int top;
int entry[MAX];
}stack;

void createStack(stack *s){
s->top=-1;
}

Boolean IsStackEmpty(const stack *s){
return(s->top==-1);
}

Boolean IsStackFull(const stack *s){
return(s->top==MAX-1);
}

void push(stack *s,int item){
    if(IsStackFull(s)){
        printf("Stack is full\n");
        exit(1);
    }else{
        s->entry[++s->top]=item;
        printf("%d pushed to stack\n",item);
    }
}

void pop(stack *s)
{
    int item;
    if(IsStackEmpty(s))
    {
        printf("Stack is empty\n");
        exit(1);
    }
    else{
        item=s->entry[s->top--];
        printf("%d popped from the stack",item);
    }
}

void main()
{
    stack *s;
    createStack(&s);
    push(&s,1);
    push(&s,2);
    push(&s,3);
    push(&s,4);
    pop(&s);
}

有人可以解决这个问题吗?

【问题讨论】:

  • 这似乎是学习如何使用调试器的好时机。首先要捕获崩溃(这就是您所拥有的),找到它们在代码中发生的位置,并检查崩溃位置处所有相关变量的值。然后,您还可以使用它逐语句逐句执行代码,同时监视变量及其值以查看它们如何变化。
  • 一个提示:在main 函数中&amp;s 的类型是stack **。不是createStack(或pop)所期待的,是吗?你的编译器应该能够发出警告,所以请听你的编译器。
  • 作为@Someprogrammerdude 所说的额外建议,您可以使用this 非常酷的工具

标签: c data-structures stack


【解决方案1】:

根本没有分配stack。这个

void main()
{
    stack *s;

只给你一个堆栈指针。

改成

void main()
{
    stack s;

获取堆栈对象。

注意:只要 MAX 相对较小,在 main 中将堆栈创建为局部变量即可。如果您将 MAX 更改为一个巨大的值(例如 #define MAX 5000000),最好使用 malloc 分配内存。请参阅@ralfhtp 的回答。

顺便说一句:启用编译器警告。您将 stack** 传递给期望 stack* 的东西,编译器会警告您,您可能已经找到了错误。

【讨论】:

    【解决方案2】:

    奇怪的是,你正在用你当前的代码破坏你机器的堆栈,当我编译它时:

    1 pushed to stack
    2 pushed to stack
    3 pushed to stack
    4 pushed to stack
    *** stack smashing detected ***: <unknown> terminated
    

    4386427 的回答是对的,尤其是编译器警告这一点。或者,您可以使用 malloc() 在机器的堆(动态内存)中构建您的堆栈:

    struct stack *s = malloc (sizeof (struct stack))
    

    memory allocation in Stack and Heap

    如果你 malloc 堆上的内存,你必须将 main() all &amp;s 更改为 s

    void main()
    {
    
        struct stack *s = malloc(sizeof(struct stack));
        createStack(s);
        push(s,1);
        push(s,2);
        push(s,3);
        push(s,4);
        pop(s);
        free(s);  // release allocated memory
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-12
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 2018-12-30
      • 2017-06-16
      • 2019-01-21
      相关资源
      最近更新 更多