Мне нужно реализовать очередь на 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. Однако я не понимаю, как это возможно... Почему это происходит?
(Моя тестовая программа просто запускает цикл for от 0 до > 4, вызывая enqueue со значением customerData, равным i).
element = &a;
Вы вставляете указатель на локальную переменную в свою очередь, после возврата функции локальная переменная больше не существует, а очередь содержит висячий указатель.malloc
память,struct fifo_element *element = malloc(sizeof *element);
. - person Daniel Fischer   schedule 25.11.2012