[英]Tried implementing stack through structure in C but getting Runtime Error for the below code. Can anyone explain and point out as to what went wrong?
Here's an inline link to Github stack_implementation_using_structure这是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");
}
The return type of the main
function should be int
, not void
, and for a main
with no parameters, the parameter list should be void
: main
function 的返回类型应该是int
,而不是void
,对于没有参数的main
,参数列表应该是void
:
int main (void)
{
s.top = -1;
/* ... */
return 0; // can be omitted - see description below.
}
Although the C standard allows main
's execution to reach the end of the function without executing a return
statement, I like to add a return 0;
虽然 C 标准允许
main
的执行到达 function 的末尾而不执行return
语句,但我喜欢添加一个return 0;
for portability with earlier versions of the C standard that did not have this feature.为了便于使用没有此功能的早期版本的 C 标准。
It worked for me but be careful you're trying to put 6 elements in the stack with an array of 5 elements (with the MAXSIZE at 5).它对我有用,但要小心你试图将 6 个元素放入堆栈中,其中包含 5 个元素的数组(MAXSIZE 为 5)。 The last one will not be considered and it can create bigger problems.
最后一个不会被考虑,它会产生更大的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.