2012-11-24 75 views
1

我需要在C語言中爲一個作業項目的一小部分實現一個隊列。我已經用多種語言做了幾年,所以我很驚訝我有這麼多麻煩。我的問題是Head的價值不斷被改變爲最新增值。FIFO隊列頭指針不正確

這是到目前爲止我的代碼:

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;是導致頭數值改變。但是,我不明白這是怎麼可能的......爲什麼會發生這種情況?

(我的測試程序只運行一個for循環從0-> 4,調用en的customerData值爲i)。

+3

'元素=&A;'你要插入一個指向您的隊列中的局部變量,函數返回後,局部變量不存在了,而隊列包含一個懸掛指針。 'malloc'內存,'struct fifo_element * element = malloc(sizeof * element);'。 –

+1

做一個*巨大的好處,不要嘗試使用一些哨兵節點作爲你的隊列是否爲「空」的符號。正確管理尾部和頭部指針,使其指向隊列中的有效內容*,如果隊列爲空,則指向NULL。如果你嚴格遵守這個標準,其餘的將實際寫出自己。 – WhozCraig

+0

謝謝@DanielFischer就是這樣。 – user1287523

回答

0
element = &a; 

你插入一個指向一個局部變量在隊列中時,函數返回後,局部變量不存在了,而隊列包含一個懸擺指針。

malloc()內存:

struct fifo_element *element = malloc(sizeof *element); 
+0

只是讓丹尼爾的評論成爲一個答案,所以這不會顯示在* unanswered *下。 – Mike