尝试通过 C 中的结构实现堆栈,但以下代码出现运行时错误。任何人都可以解释并指出哪里出了问题吗?
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?
这是 link 到 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");
}
main
函数的return类型应该是int
,不是void
,对于没有参数的main
,参数列表应该是 void
:
int main (void)
{
s.top = -1;
/* ... */
return 0; // can be omitted - see description below.
}
虽然C标准允许main
的执行到达函数末尾而不执行return
语句,但我想添加一个return 0;
以便与早期版本的可移植性没有此功能的 C 标准。
它对我有用,但请注意,您正在尝试将 6 个元素放入具有 5 个元素的数组(MAXSIZE 为 5)的堆栈中。最后一个不会被考虑,它会产生更大的问题。
这是 link 到 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");
}
main
函数的return类型应该是int
,不是void
,对于没有参数的main
,参数列表应该是 void
:
int main (void)
{
s.top = -1;
/* ... */
return 0; // can be omitted - see description below.
}
虽然C标准允许main
的执行到达函数末尾而不执行return
语句,但我想添加一个return 0;
以便与早期版本的可移植性没有此功能的 C 标准。
它对我有用,但请注意,您正在尝试将 6 个元素放入具有 5 个元素的数组(MAXSIZE 为 5)的堆栈中。最后一个不会被考虑,它会产生更大的问题。