You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言编写队列程序时数组自动出现垃圾值问题求助

顺序队列垃圾值、容量不符问题修复

代码存在的核心错误

实现中有3处直接导致异常的逻辑错误,还有1处冗余无效代码:

  • 出队逻辑错误修改队列总容量:dequeue分支中size+=1;属于完全错误的逻辑,基于变长数组实现的顺序队列初始化后总容量固定,出队仅需移动队头指针,修改size会直接导致溢出判断失效、数组越界访问。
  • 入队溢出判断边界错误:当前满队判断用的是rear == size - 1,但实现逻辑里rear指向的是下一个可写入的空位置,长度为size的数组下标范围是0~size-1,当rear等于size时才是真正的队满,原判断会导致队列实际只能存入size-1个元素。
  • 队列遍历边界错误:display分支的循环条件写为i <= rear,但queue[rear]是从未被赋值的预留位置,存储的是栈内存的随机垃圾值,这就是看到额外无效元素的直接原因,遍历只需要走到rear的前一个位置即可。
  • 冗余无效声明:代码开头声明的enqueue()、dequeue()、display()三个函数没有任何实现也从未被调用,属于无效代码可以直接删除。

修正后代码

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int main(){
    int size;
    printf("Enter the size of the queue : ");
    scanf("%d", &size);
    int choice, element;
    int queue[size];
    int front = 0;
    int rear = 0;
    while(true){
        printf("Queue Operations\nPress 1 for Enqueue\nPress 2 for Dequeue\nPress 3 for Display\nPress 4 for exit\n");
        scanf("%d", &choice);

        switch(choice){
            case 1:{
                if(rear == size){
                    printf("Overflow!\n");
                }
                else{
                    printf("Enter the element you want to enqueue : ");
                    scanf("%d", &element);
                    queue[rear] = element;
                    rear++;
                }
                break;
            }
            case 2:{
                if(front == rear){
                    printf("Underflow!\n");
                }
                else{
                    printf("The element deleted is %d\n", queue[front]);
                    front++;
                }
                break;
            }
            case 3:{
                if(front == rear){
                    printf("Queue is empty.\n");
                }
                else{
                    for(int i = front; i < rear; i++){
                        printf("%d ", queue[i]);
                    }
                    printf("\n");
                }
                break;
            }
            case 4:{
                exit(0);
            }
            default:{
                printf("Invalid Choice.\nTry again.\n");
                break;
            }
        }
    }
    return 0;
}

补充提示:当前实现是最基础的顺序队列,出队后的前置空间无法重复利用,多次入队出队操作后会出现「假溢出」(队列实际还有空闲空间但判定为已满),如果需要复用存储空间可以进一步实现循环队列逻辑。

内容的提问来源于stack exchange,提问作者Zenom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 05:45:54