2016-05-01 8 views
-3

私はプログラミングにおいて非常に新しいです。配列(循環キュー)を使ってキューを実装するプログラムを作成したかったのです。私は、キュー機能から要素を削除する&を挿入するのは正しいと思いますが、表示機能には問題があります。キューがいっぱいになると、要素を挿入しようとすると関数ごとに「QUEUE FULL」と表示されず、要素の横にいくつかのガベージ値が表示されます。このCコードのバグはどこですか?

#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; 
} 
+3

デバッガを使用しましたか? – MikeCAT

+3

番号を分けるのに 'm 'の代わりに' m + 1'が使われるのはなぜですか?アレイの範囲外にアクセスする危険性があります! – MikeCAT

+0

私はVisual Studio 12 @ MikeCAT – Fsalad

答えて

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... 
} 
+0

これは正常に動作します – Fsalad

1

問題がenQueue()機能でif状態です。

fは-1であり、プログラム全体で変更されることはありません。また、sは決して-1にならないため、条件は決してうまくいかないでしょう。

if条件をs == fからs==mに変更します。

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

プログラムをもう一度実行します。 私はそれをテストしました。

1

あなたは配列の要素の数を追跡できるように、コードはかなりの数の問題を抱えている時間を提示

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 
関連する問題