![](/img/trans.png)
[英]Unexpected output after running this little bit strange c code. Can anyone explain how this happened?
[英]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?
這是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
function 的返回類型應該是int
,而不是void
,對於沒有參數的main
,參數列表應該是void
:
int main (void)
{
s.top = -1;
/* ... */
return 0; // can be omitted - see description below.
}
雖然 C 標准允許main
的執行到達 function 的末尾而不執行return
語句,但我喜歡添加一個return 0;
為了便於使用沒有此功能的早期版本的 C 標准。
它對我有用,但要小心你試圖將 6 個元素放入堆棧中,其中包含 5 個元素的數組(MAXSIZE 為 5)。 最后一個不會被考慮,它會產生更大的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.