2017-01-04 12 views
-2

C言語でキューADTを実装したいと思います。私のキューのサイズが0であると言うのはなぜですか?

私は、次があります。出力は0と1である理由

// node structure: 

typedef int ElementType; 
typedef struct node { 
    ElementType key; 
    struct node* left_child; 
    struct node* right_sib; 
}* Node; 
typedef Node Item; 

// queue structure: 

struct queue { 
    Item* contents; 
    int head; 
    int tail; 
    int dim; 
}; 
typedef struct queue* Queue; 


Queue initqueue();     // create a queue 
int queueEmpty(Queue q);   // queue empty? 
void enqueue(Queue q, Item elem); // insert item 
int size(Queue q);     // size of the queue? 


Queue initqueue() { 
    Queue q = (Queue)malloc(sizeof(struct queue)); 
    q -> contents = (Item*)malloc(sizeof(Item)); 
    q -> head = 0; 
    q -> tail = 0; 
    q -> dim = 1; 
    return q; 
} 

int queueEmpty(Queue q) { 
    return (q -> head == q -> tail); 
} 

void enqueue(Queue q, Item elem) { 
    if (q -> head == (q -> tail % q -> dim) + 1 || q -> dim == 1) 
     q -> contents = (Item*)realloc(q -> contents, (q -> dim) * 2); 
    q -> contents[q -> tail] = elem; 
    q -> tail = (q -> tail + 1) % (q -> dim); 
} 

int size(Queue q) { 
    if (q -> tail < q -> head) 
     return ((q -> dim) - (q -> head) + (q -> tail) - 1); 
    else 
     return (q -> tail - q -> head); 
} 


int main() { 
    Queue q; 
    Item i = (Item)malloc(sizeof(struct node)); 
    i -> key = 4; 
    q = initqueue(); 
    enqueue(q, i); 
    printf("%d\n", queueEmpty(q)); 
    printf("%d\n", size(q)); 

    return 0; 
} 

が、私は理解していない、それは、キューが空にされており、そのサイズは、あなたがq->dimを調整するのを忘れ0

+1

['malloc()'と 'C 'のファミリの戻り値をキャストしない理由についてのこのディスカッションを参照してください。](http://stackoverflow.com/q/605845/2173917)。 –

+2

SOはデバッグサービスではありません。シンボルでコンパイルするには、デバッガ内でコードを実行し、プログラムを1行ずつトレースして、関連する変数の値を調べ、実際に何が起こっているのかを調べます。 *具体的な質問が発生した場合は、ここに戻って自由に感じてください。 – alk

+1

それを信じてもいいですが、プログラムは 'typedef'を追加することによって、さらに難しくすることができます。あなたが何かに持っている名前が多くなればなるほど、その使用を追跡することは難しくなります。 – StoryTeller

答えて

0

ですしたがって、enqueueの後にはq->tailはまだゼロ(1 % 1)です。

関連する問題