C语言静态栈代码运行异常求助:溢出判断失效、显示重复等问题
C语言静态栈代码问题修复
问题1:push函数溢出时仍接收输入,无提示
错误原因:push函数中先执行scanf接收输入,再判断栈是否已满。即便栈已满,输入操作已完成,溢出提示逻辑被跳过。
修复方法:先判断栈状态,仅当栈未满时才执行输入和压栈操作。
修改后的push函数:
void push() { int x; if (top == N - 1) { printf("Overflow\n"); return; // 直接返回,终止后续操作 } printf("Enter data: "); scanf("%d", &x); top++; stack[top] = x; }
问题2:display函数输出所有元素均为同一个值
错误原因:display循环中始终访问stack[top](栈顶元素),未使用循环变量i遍历栈内不同位置的元素。
修复方法:将stack[top]改为stack[i],遍历栈内每个元素。
修改后的display函数:
void display() { int i; if (top == -1) { printf("Stack is empty\n"); return; } printf("Stack elements:\n"); for (i = top; i >= 0; i--) { printf("%d\n", stack[i]); } }
问题3:void main()与getch()报错(已解决)
说明:void main不符合C标准,标准要求入口函数为int main()并返回整数值。getch()属于非标准库函数,标准C环境无法识别,移除该函数并改用标准int main()是正确的,此问题已无需额外修改。
完整修复后的代码
#include <stdio.h> #include <stdlib.h> #define N 5 int stack[N]; int top = -1; void push() { int x; if (top == N - 1) { printf("Overflow\n"); return; } printf("Enter data: "); scanf("%d", &x); top++; stack[top] = x; } void pop() { int item; if (top == -1) { printf("Underflow\n"); return; } item = stack[top]; top--; printf("Popped element: %d\n", item); } void peek() { if (top == -1) { printf("Underflow\n"); return; } printf("Top element: %d\n", stack[top]); } void display() { int i; if (top == -1) { printf("Stack is empty\n"); return; } printf("Stack elements:\n"); for (i = top; i >= 0; i--) { printf("%d\n", stack[i]); } } int main() { int ch; do { printf("\n1.push\n2.pop\n3.peek\n4.display\n5.exit\nEnter your choice: "); scanf("%d", &ch); switch (ch) { case 1: push(); break; case 2: pop(); break; case 3: peek(); break; case 4: display(); break; case 5: exit(0); break; default: printf("Invalid key pressed\n"); break; } } while (ch != 5); // 修正循环条件,匹配菜单退出选项 return 0; }
额外细节优化:
- 修正main函数循环条件,原
ch != 0与菜单退出选项5不匹配,改为ch !=5确保正常退出 - 各函数添加换行符
\n,优化输出可读性 - 为pop、peek函数补充明确的操作提示文本
内容的提问来源于stack exchange,提问作者Ashitosh bendre
相关产品推荐
相关产品推荐

