尝试在C中通过结构实现堆栈,但以下代码出现运行时错误。谁能解释和指出出了什么问题?

问题描述 投票:0回答:2

这里是到Github的嵌入式链接stack_implementation_using_structure

#include <stdio.h>
#define MAXSIZE 5

struct stack
{
    int stk[MAXSIZE];
    int top;
};
typedef struct stack STACK;
STACK s;

void push(int);
void pop(void);
void display(void);

void main ()
{
    s.top = -1;
    push(1);
    push(2);
    push(3);
    push(4);
    push(5);
    display();
    push(6);
    pop();
    pop();
    pop();
    pop();
    pop();
    pop();
}
/*  Function to add an element to the stack */
void push (int num)
{
    if (s.top == (MAXSIZE - 1))
    {
        printf ("Stack is Full\n");
    }
    else
    {
        s.top++;
        s.stk[s.top] = num;
    }
}
/*  Function to delete an element from the stack */
void pop ()
{
    if (s.top == - 1)
    {
        printf ("Stack is Empty\n");
    }
    else
    {
        printf ("poped element is = %d\n", s.stk[s.top]);
        s.top--;
    }
}
/*  Function to display the status of the stack */
void display ()
{
    int i;
    if (s.top == -1)
    {
        printf ("Stack is empty\n");
    }
    else
    {
        printf ("The status of the stack is \n");
        for (i = s.top; i >= 0; i--)
        {
            printf ("%d ", s.stk[i]);
        }
    }
    printf ("\n");
}
c stack runtime-error structure
2个回答
0
投票

main函数的返回类型应该是int,而不是void,对于没有参数的main,参数列表应该是void

int main (void)
{
    s.top = -1;
    /* ... */
    return 0; // can be omitted - see description below.
}

尽管C标准允许main的执行在不执行return语句的情况下到达函数的结尾,但是我还是想添加return 0;以便与不具有此功能的C标准的早期版本进行移植。功能。


0
投票

它对我有用,但是要小心,您要尝试将6个元素与5个元素组成的数组放入堆栈中(MAXSIZE为5)。最后一个将不予考虑,它会带来更大的问题。

© www.soinside.com 2019 - 2024. All rights reserved.