我需要为作业项目的一小部分实现 C 中的队列。我已经用各种语言做了几年,所以我很惊讶我遇到了这么多麻烦。我的问题是 Head 的值不断更改为最近增加的值。
到目前为止,这是我的代码:
void Enqueue( fifo* queue, int customerData)
{
//Determine if a head or tail exists
int tailExists = 0;
if(queue->tail->customerId >= 0){
tailExists = 1;
}
//Create new elements
struct fifo_element a, *element;
element = &a;
if(tailExists == 1)
printf("test2 the head is %d\t", queue->head->customerId);
element->customerId = customerData;
if(tailExists == 1)
printf("test3 the head is %d\t", queue->head->customerId);
//Set the next element to the current tail
if(tailExists == 1)
element->next = queue->tail;
else
element->next = NULL;
//Set the prev element to null
element->prev = NULL;
//Set the last element's previous to the new element
if(tailExists == 1){
queue->tail->prev = element;
}
//Set the tail to the new element
queue->tail = element;
if(tailExists == 0){
queue->head = element;
}
printf("the head is %d\t", queue->head->customerId);
printf("the tail is %d\t", queue->tail->customerId);
}
根据 printf 行,行 element->customerId = customerData;
导致 Head 值发生变化。但是,我不明白这怎么可能……为什么会这样?
(我的测试程序只是从 0->4 运行一个 for 循环,使用 customerData 值为 i 调用 enqueue)。
最佳答案
element = &a;
您在队列中插入一个指向局部变量的指针,函数返回后,局部变量不再存在,并且队列包含一个悬空指针。
malloc()
内存:
struct fifo_element *element = malloc(sizeof *element);
关于c - FIFO 队列头指针不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13544961/