C语言Queue的Display功能异常:选择选项4后程序终止求助
队列DISPLAY功能导致程序终止的修复方案
以下是针对队列展示功能触发程序终止的常见问题排查与修复方法:
一、数组实现队列的典型问题修复
如果你的队列是基于数组+front/rear指针实现的,最常见的错误是遍历过程中修改了原队列的指针,或者数组越界访问:
- 错误示例(直接修改
front指针,破坏队列结构):
void display() { while (front != rear) { printf("%s ", queue[front]); front++; // 直接移动了原队列的front指针 } }
- 修复方案:用临时变量替代原指针遍历,循环队列记得取模避免越界:
#define MAX_SIZE 100 char* queue[MAX_SIZE]; int front = 0, rear = 0; void display() { if (front == rear) { printf("队列是空的\n"); return; } int temp = front; // 用临时变量遍历,不修改原指针 while (temp != rear) { printf("%s ", queue[temp]); temp = (temp + 1) % MAX_SIZE; // 循环队列必须取模 } printf("\n"); }
二、链表实现队列的典型问题修复
如果是链表结构的队列,多因空指针访问或遍历逻辑错误导致崩溃:
- 错误示例(未判断队列为空就访问节点,或遍历终止条件错误):
struct Node { char* data; struct Node* next; }; struct Node *front = NULL, *rear = NULL; void display() { struct Node *current = front; while (current->next != NULL) { // 队列为空时current是NULL,直接访问->next会触发崩溃 printf("%s ", current->data); current = current->next; } }
- 修复方案:先判断队列是否为空,遍历到节点为NULL为止:
void display() { if (front == NULL) { printf("队列是空的\n"); return; } struct Node *current = front; while (current != NULL) { printf("%s ", current->data); current = current->next; } printf("\n"); }
三、菜单分支的隐藏错误检查
有时候问题不在DISPLAY函数本身,而是菜单的switch-case分支里误加了终止程序的代码:
- 错误示例:
switch(choice) { case 4: display(); exit(0); // 误写了退出语句,导致显示后直接终止程序 break; }
- 修复方案:移除多余的
exit(0),保留break即可。
内容的提问来源于stack exchange,提问作者anna
相关产品推荐
相关产品推荐

