【问题标题】:Where is the bug in this C code? [closed]这个 C 代码中的错误在哪里? [关闭]
【发布时间】:2016-05-01 05:50:20
【问题描述】:

我是编程新手。我想编写一个程序来实现带有数组的队列(循环队列)。我认为队列函数中的插入和删除元素是正确的,但是显示函数存在一些问题。当队列已满时,如果我尝试插入更多元素,它不会按照函数显示“QUEUE FULL”,它会在元素旁边显示一些垃圾值。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>  
#include <ctype.h>
#include <string.h>

#define m 3   // maximum size of array
int Q[m];
int f=-1,r=-1,s;        //f=front,r=rear,s=rear in another term for finding wheather is 

queue full


int enQueue(int item){
    s = (r+1)%(m+1);
    if(f == s)
        printf("\nQUEUE FULL"); 
    else{
        Q[s] = item;
        r = s;
    }

return 0;
}


int deQueue(){
    int item;
    if(f == r)
        printf("\nQUEUE UNDERFLOW");
    else{   
        f = (f+1)%(m+1);
        item = Q[f];
        Q[f] = NULL;
    }

return 0;
}

void displayQueue(){
    int i;
    if(f == r) 
        printf(" \n The queue is empty\n");
    else {
        printf("\nQUEUE IS : \n");
        for(i=f+1; i<=s; i++) {
            printf("%d\t", Q[i]);
        }
        printf("\n\n********************************************");
    }

}



int main(){
    int item,i,j;

    while (1){
        printf("\n\nENTER ITEM TO INSERT : ");
        scanf("%d", &item);

        enQueue(item);
        displayQueue();
    }

 _getch();
 return 0;
}

【问题讨论】:

  • 你用过调试器吗?
  • 为什么用m+1而不是m来划分数字?存在访问超出数组范围的风险!
  • 我在 Visual Studio 12 @ MikeCAT 中编写了这段代码
  • 也许你可以集中关注我们,写出什么是错误?也许您可以展示预期结果与您得到的结果?
  • Visual Studio 一个调试器。请通过准确描述预期输出和实际输出(不仅仅是“存在一些问题”)来改进您的问题。

标签: c data-structures queue


【解决方案1】:

代码有很多问题。此回复仅涉及问题范围内的内容。希望对您有所帮助。

int enQueue(int item){
   if(r+1 >= m)   //check against queue size first...
        printf("\nQUEUE FULL"); 
   else{
        s = (r+1)%(m);
        Q[s] = item;
        r = s;
    }
return 0;        //the return value part could be written better...
}

【讨论】:

    【解决方案2】:

    你可以尝试一个新的计数变量,这样你就可以跟踪数组中元素的数量。

    initialize the count to 0 as global
    if enque 
    check count for the overflow 
     if not
      add element and increase the count
    if deque
    check count for the underflow
     if not
      delete the element and decrese the count
    

    【讨论】:

      【解决方案3】:

      问题出在enQueue() 函数中的if 条件中。

      f 为 -1,在整个程序中不会发生变化,s 永远不会是 -1,因此条件永远不会成立。

      将if条件从s == f改为s==m,即。

      if(s == m)
          printf("Queue is full");
      

      再次运行程序。 我已经测试过了。

      【讨论】:

        最近更新 更多