【发布时间】:2012-11-24 19:50:57
【问题描述】:
我需要在 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 循环,调用 enqueue,customerData 值为 i)。
【问题讨论】:
-
element = &a;您在队列中插入一个指向局部变量的指针,函数返回后,局部变量不再存在,并且队列包含一个悬空指针。malloc内存,struct fifo_element *element = malloc(sizeof *element);。 -
帮自己一个巨大的忙,不要尝试使用某个哨兵节点作为队列是否“空”的标志。正确管理您的尾指针和头指针,使其指向队列in 中的有效内容,如果队列为空,则为NULL。如果您严格遵守这一点,其余部分实际上会自行编写。
-
谢谢@DanielFischer 就是这样。
标签: c pointers data-structures queue fifo