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

在C中实现队列时遇到问题,c,queue,C,Queue,我正在尝试用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 }; //初

我正在尝试用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);

}

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

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

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);
注意操作符
的地址。你不必(也不能)在这里释放队列


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

struct queue*newQueue=malloc(sizeof(struct queue))
intk=*(q->后)+1米林德说的话,另外你应该给新队列打电话。按原样,
newQueue
指针(在
main
new\u Queue
中)都不指向任何地方;q->rear=NULL好的,伙计们,非常感谢你们的反馈!我们将对此进行调查,并让您知道它是如何运行的:)它是如何工作的!:)谢谢大家!实际上,我将队列调整为循环缓冲区,因为这正是我所需要的。无论如何,当我排队等待一个整数时,我似乎在init_队列函数中得到了一个线程1:EXC_BAD_访问(代码1…)。。。它出现在行q->count=0;上。。。有人知道为什么吗?让我猜猜:因为
q
是一个未初始化的指针,它不指向任何地方,所以用
*
->
解除对它的引用是未定义的行为。(我以为您已经将队列实现为循环缓冲区,并将
前端
后端
作为数据开始和结束位置的标记。)我看不出我做错了什么:/我输入了init函数的代码,与上面的
void queue_init(struct queue*q)完全相同{q->count=0;q->front=q->array;q->rear=q->array;}
“错误访问”告诉您访问了无法访问的内存。很可能您正在取消对未初始化或
NULL
指针的引用。您应该熟悉调试,以便解决此类问题。