我附上了运行时错误的屏幕截图。
此代码将创建一个堆栈
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
// Declared a Structure with top,an array as its members
struct Stack {
int items[SIZE],top;
};
//push method inserts an element in the stack
void push(struct Stack *s1,int x){
s1->items[++s1->top]=x;
}
// pop method is for Removing the Elements
void pop(struct Stack* s1){
printf("Before pop the Top is %d ",s1->top);
int a=s1->items[s1->top--];
printf("After pop the Top is %d",s1->top);
}
//Main method
void main() {
struct Stack s,*s1;
struct Stack top = {-1}; //Initializing Top variable in Structure
int n;
//loop to insert the elements
for(int i=0;i<SIZE;i++){
printf("Enter the elements to be pushed");
scanf("%d",&n);
push( s1, n);
}
pop(s1);
pop(s1);
printf("The Elements of the Stack after performing all the operations are ");
// Print the elements of the stack
for(int i=0;i<SIZE;i++) {
printf("%d",s1->items[SIZE]);
}
}
最佳答案
有很多问题:
这是您的程序的修正版本。所有更正均已发表评论。 代码仍然很草率(例如,没有错误检查,变量名称毫无意义),但至少它可以工作。
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
struct Stack {
int items[SIZE];
int top; // better readability
};
// push method inserts an element in the stack
void push(struct Stack *s1, int x) {
s1->items[++s1->top] = x;
}
// pop method is for removing ONE Element // COMMENT CORRECTED
int pop(struct Stack* s1) { // we need to return the popped element
printf("Before pop the Top is %d\n", s1->top);
int a = s1->items[s1->top--];
printf("After pop the Top is %d\n", s1->top);
return a;
}
int main() { // main must return an int
struct Stack s; // removed useless s1 ansd top variables
// BTW s1 was an uninitialized pointer so this was
// totally wrong
int n;
s.top = -1; // initialize top correctly
// struct Stack s = {-1} will not initialize s.top !!
for (int i = 0; i<SIZE; i++) {
printf("Enter the elements to be pushed: ");
scanf("%d", &n);
push(&s, n);
}
printf("First popped value: %d\n", pop(&s)); // print popped elements
printf("Second popped value: %d\n", pop(&s));
printf("The Elements of the Stack after performing all the operations are: ");
for (int i = 0; i <= s.top; i++) { //i <= top instead of i < SIZE
printf("%d\n", s.items[i]); // s.items[i] instead of s.items[SIZE]
}
}
关于c - 我在代码块中编写的堆栈实现代码编译成功,但在运行时显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49103652/