在 C 中实现队列时遇到问题

Trouble implementing a queue in C

我正在尝试用 c 实现一个队列。我已经在我的代码中实现了一个入队函数。但是,当我对其进行测试时,我没有得到所需的输出。有人可以告诉我我做错了什么吗?

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
 };

//初始化队列

struct queue * new_Queue()
{

     struct queue *q;
     q->count=0;
     q->front=&q->array[-1];
     q->rear=&q->array[-1];

     return q;
};

int queueCount(struct queue *q)
{
     return q->count;
}

int isFull(struct queue *q)
{
     if(q->count==30){
         printf("%s","Buffer is full!");
         return 1;
     }

return 0;
}

int isEmpty(struct queue *q)
{

     if(q->count==0){
         printf("%s","Queue 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);

     q->array[k]=i;
     printf("enque success!");


     return 1;
}

int main(int argc, char**argv)
{
     int i=10;

     struct queue *newQueue;

     enqueue(newQueue,i);
     int j= queueCount(newQueue);
     printf("%d",j);

}

您的队列需要内存。目前,您有一个指向内存中随机位置的未初始化指针。取消引用该指针是未定义的行为,很可能会给您带来段错误。

您必须决定如何存储您的队列。您可以使用 malloc 在堆上分配它。这是你的函数 new_Queue 应该做的:

struct queue *new_Queue()
{
    struct queue *q = malloc(sizeof(*q));    // TO DO: Error checking

    q->count = 0;
    q->front = q->array;
    q->rear = q->array;

    return q;
}

您的客户端代码如下所示:

struct *q = new_Queue();

enqueue(q, x);
// Do more stuff ...

free(q);     // Release resources

队列结构不大。您也可以在堆栈上分配它。在那种情况下,您需要一个初始化函数:

void queue_init(struct queue *q)
{
    q->count = 0;
    q->front = q->array;
    q->rear = q->array;
}

并这样称呼它:

struct queue *q;

queue_init(&q);
enqueue(&q, 12);

注意运算符的地址 &。您不必(也不能)free 在此处排队。

您无法访问索引 -1 处的数组。您可以使 front 成为下一个要出队的元素,而 rear 指向下一个元素入队的 space 。在循环缓冲区中,这将使空列表和满列表的情况无法区分,但您可以使用 count 来区分它们。