【发布时间】:2015-03-01 16:06:21
【问题描述】:
我在用 C 语言实现一个充当循环缓冲区的 FIFO 队列时遇到问题。到目前为止,我只设法编写了一个入队方法,并且我遇到了输出问题。它没有显示它应该显示的内容,我不确定问题出在哪里。
代码如下:
struct queue
{
int array[30];
int *front; //pointer to front of queue
int *rear; //pointer to rear of queue
int count; //counts number of elements in queue
};
//initialising a queue
struct queue *init_Queue(){
struct queue * q = malloc(sizeof (q));
q->count=0;
q->front=q->array;
q->rear=q->array;
return q;
}
int isFull(struct queue *q){
if(q->count==30){
printf("\n Buffer is full!");
return 1;
}
return 0;
}
int isEmpty(struct queue *q){
if(q->count==0){
printf("\n Buffer is empty!");
return 1;
}
return 0;
}
int enqueue(struct queue * q,int i){
if(isFull(q)){
return 0;
}
if(isEmpty(q)){
q->front+1;
}
int k=*(q->rear)+1;
printf("\n %d",k);
q->array[k]=i;
q->rear+1;
printf("\n Enqueue success!");
q->count++;
return 1;
}
int main(int argc, char**argv)
{
int i=10;
int k=12;
struct queue *q=init_Queue();
enqueue(q,i);
int j= q->count;
printf("\n %d",j);
printf("\n %d",q->array[0]);
printf("\n %d",q->rear);
enqueue(q,k);
int z= q->count;
printf("\n %d", z);
printf("\n %d", q->array[1]);
printf("\n %d",q->rear);
free(q);
}
输出如下:
Buffer is empty!
1
Enqueue success!
1 <<**value of count**
0 << **value stored in array[0]...it should say 10**
1070400 << **q->rear...should be pointing to 10?**
1
Enqueue success!
2 **<<value of count**
12 **<<value stored in array[1]**
1070400 **<< q-rear...should be incremented and pointing to 12?**
Program ended with exit code: 0
【问题讨论】:
-
附带说明,
%p应该用于 printf 指针。 -
在调试器中逐行遍历
enqueue函数,看看会发生什么以及所有指针和值都设置了什么。 -
malloc(sizeof(*q))!!