使用结构体实现C数组栈时,pop与peep操作返回垃圾值的原因?
栈操作返回垃圾值的问题修复
你的代码存在两个关键逻辑错误,导致push、pop操作出现垃圾值,以下是问题分析和修复方案:
错误1:Push函数的数组索引越界
初始时top被设为-1,你当前的push逻辑是先给st[s->top]赋值,再执行top++。第一次执行push时,s->top的值是-1,访问st[-1]属于数组越界,会往非法内存区域写入数据,后续读取自然会得到垃圾值。
修正后的Push函数:
void push(struct stack *s, int item){ if(s->top == SIZE -1){ printf("Stack is full! \n"); } else { s->top++; // 先自增top,让索引从0开始 s->st[s->top] = item; // 也可以合并成一行:s->st[++s->top] = item; } }
错误2:Pop函数的执行顺序错误
你在pop函数中先执行return s->st[s->top],之后的s->top--永远不会被执行——因为return语句会直接终止函数。这会导致top指针永远不会递减,不仅会重复返回同一个值,还会让栈永远无法回到空状态。
另外,栈空时pop函数原本没有返回值,这会触发未定义行为,所以需要补充一个标记返回值。
修正后的Pop函数:
int pop(struct stack *s){ if(s->top == -1){ printf("Stack is empty! \n"); return -1; // 栈空时返回标记值,可根据需求调整 } else { int val = s->st[s->top]; // 先保存栈顶元素 s->top--; // 再递减top指针 return val; } }
完整修正代码
#include<stdio.h> #define SIZE 10 struct stack{ int st[SIZE]; int top; }; void init_stack(struct stack *s); void push(struct stack *s, int item); int pop(struct stack *s); void peep(struct stack *s); int main(){ // 符合C标准的main返回类型 int opt, ele; struct stack s; init_stack(&s); label: printf("Enter the operation you want to perform: \n 1. Push \n 2. Pop \n 3. Peep \n 4. Exit \n"); scanf("%d", &opt); switch(opt){ case 1: printf("Enter the element you want to push: "); scanf("%d", &ele); push(&s, ele); goto label; case 2: int popped = pop(&s); if(popped != -1){ // 避免栈空时打印无效值 printf("Popped item: %d\n", popped); } goto label; case 3: peep(&s); goto label; case 4: break; default: printf("Please enter the valid option!\n"); goto label; } return 0; } void init_stack(struct stack *s){ s->top = -1; } void push(struct stack *s, int item){ if(s->top == SIZE -1){ printf("Stack is full! \n"); } else { s->top++; s->st[s->top] = item; } } int pop(struct stack *s){ if(s->top == -1){ printf("Stack is empty! \n"); return -1; } else { int val = s->st[s->top]; s->top--; return val; } } void peep(struct stack *s){ if(s->top == -1){ printf("Stack is empty! \n"); } else { printf("Top item in the stack: %d \n", s->st[s->top]); } }
额外提示:C标准中main函数的返回类型应为int,代码中已同步修正;同时在pop调用处增加了判断,避免栈空时打印无效的返回值。
内容的提问来源于stack exchange,提问作者Dev
相关产品推荐
相关产品推荐

