c - 元素未插入队列中的不同位置,值未正确显示

标签 c queue

这是我的 en_queue 函数,用于在不同条件下插入新元素。

void en_queue(int *queue,int max,int front,int rear)
{
    int ch1;
    printf("\n Enter element to add->");
    scanf("%d",&ch1);
    if(front==0 && rear==(max-1))
    {
        printf("\n Caution!! Queue Overflow!!");
    }
    else if(rear==(max-1) && front>0)
    {
        rear=0;
        queue[rear]=ch1;
        printf("\n %d added to the queue where front fo the queue has room but rear does not" ,ch1);
    }
    else if(front==-1 && rear==-1)
    {
        front=rear=0;
        queue[rear]=ch1;
        printf("\n %d added to the queue where this is the first element to the queue" ,ch1);
    }
    else 
    {
        rear++;
        queue[rear]=ch1;
        printf("\n %d added to the queue where the element added in the rear" ,ch1);
    }
}

这是我的 show_queue 函数。

void show_queue(int *newqueue,int front,int rear)
{
    int i=0;
    for(i=front;i<=rear;i++)
    {
        printf("%d",newqueue[i]);
    }
}

通过打印语句,我检查元素总是被插入到第一个位置。所以,我最好的猜测是 rearfront 元素没有成功更新,但我找不到原因。另外,我至少应该通过 show_queue 函数看到正确插入的第一个值;相反,我看到的是垃圾值,但这些值是 constant 即。 4235968 每次。

更新-这是请求的主要功能。

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

#define MAX 10

void en_queue(int *,int, int, int);
void show_queue(int *,int,int);

int main()
{
    int queue[MAX],front=-1,rear=-1,ch;
    do{
        printf("\n <<Queue MENU>>");
        printf("\n 1. Add Element");
        printf("\n 2. Delete Element");
        printf("\n 3. Show Queue");
        printf("\n 4. Exit menu");
        printf("\n Enter your choice->");
        scanf("%d", &ch);

        switch(ch)
        {
            case 1: en_queue(queue,MAX,front,rear);
                break;
            /*  
            case 2: del_queue(queue,MAX,front,rear);
                 break;
             */
            case 3: printf("\n The queue is->");
                show_queue(queue,front,rear);
                break;

            case 4:exit(0);

            default: printf("\n Invalid Choice!!!");
                return 0;
        }
    } while(ch!=4);

    return 0;
}

最佳答案

您的frontrear按值传递,因此它们的更改不会在此函数之外维护。

基本上发生的事情是你的 frontrear 变量是调用函数中存在的变量的副本,比如 主要。因此,此处对其所做的更改不会反射(reflect)在调用函数中。

dequeue 也会遇到这个问题。

您可能想按照建议的相反顺序执行以下操作之一

  1. 使它们成为全局变量。 - 不推荐,风格不好,容易出错,只允许 1 个队列。
  2. 让它们成为父函数变量的指针
  3. OOP 风格,将队列做成一个struct,其中包含数组、maxfrontrear ,并将其作为指针传递。

关于c - 元素未插入队列中的不同位置,值未正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18779337/

相关文章:

c - 在 C 中使用 scanf 解析带有 2 个不同分隔符的字符串

.net - 线程、队列和工作流

c - 如何在 C 中设置 GNUPLOT 线的颜色

c - 为什么使用 typedef *after* 结构定义?

Java:我可以使用Redis db创建优先级队列并根据数据集中键的值设置优先级吗

php - Queue:push() 在 Laravel 5 中被同步处理

c# - 当它接收到新元素时,不断循环遍历线程中的列表

c++ - C++ 在磁盘上的特定位置创建队列

c - Xcode 4.6 (4H127),clang 警告 'illegal character encoding in string literal' ISO-8859-1 编码的 o-umlaut (0xF6)

c - c 中声明和定义的内存分配