C语言基于数组实现双栈排序功能运行异常问题求助
代码运行异常的核心原因
- 值传递导致栈顶指针修改无效:C语言默认采用值传递参数,你在
push、pop函数中传入的top、top2是值拷贝,函数内部修改形参B的数值不会同步到外部的全局栈顶变量,所有栈操作完成后栈顶指针始终未更新,直接导致栈逻辑完全失效。 - 判满逻辑错误:
isfull函数判断条件为B == MAXSIZE,但数组下标从0开始,栈满时栈顶指针最大值应为MAXSIZE - 1(即4),原逻辑会触发数组越界写入,引发未定义行为。 - 函数逻辑不严谨:
pop、push函数部分执行分支没有明确返回值,部分场景下会返回随机值,干扰正常逻辑。 - 冗余变量定义:
sortStack内部定义了局部数组tmpStack(大写S),但实际排序逻辑使用的是全局tmpstack(小写s),虽然不直接导致报错,但存在逻辑混淆风险。
修改方案
调整栈操作函数的参数传递方式,修正边界判断,具体修改后的完整代码如下:
#include <stdio.h> int MAXSIZE = 5; int stack[5]; int tmpstack[5]; int top = -1; int top2 = -1; int isempty(int A[], int B) { return B == -1 ? 1 : 0; } int isfull(int A[], int B) { // 修正栈满判断条件 return B == MAXSIZE - 1 ? 1 : 0; } // 栈顶参数改为指针,支持修改外部变量 int pop(int A[], int *B) { int data; if(!isempty(A, *B)) { data = A[*B]; *B = *B - 1; return data; } else { printf("Could not retrieve data, Stack is empty.\n"); return -1; } } // 栈顶参数改为指针,支持修改外部变量 void push(int data, int A[], int *B) { if(!isfull(A, *B)) { *B = *B + 1; A[*B] = data; } else { printf("Could not insert data, Stack is full.\n"); } } int sortStack(int stack[]) { // 删掉冗余的局部tmpStack定义 while (!isempty(stack, top)) { int tmp = stack[top]; pop(stack, &top); while (!isempty(tmpstack, top2) && tmpstack[top2] > tmp) { push(pop(tmpstack, &top2), stack, &top); } push(tmp, tmpstack, &top2); } return 0; } int main() { int n, a; n = 5; for(int i = 0; i < n ; ++i) { scanf("%d", &a); // 传入栈顶指针地址 push(a, stack, &top); } sortStack(stack); while (!isempty(tmpstack, top2)) { printf("%d ", tmpstack[top2]); pop(tmpstack, &top2); } return 0; }
内容的提问来源于stack exchange,提问作者Rohi.98
相关产品推荐
相关产品推荐

