2011-01-28 36 views
0

我的第一個C分配是創建一個隊列。我正在使用基於數組的實現而不是鏈接列表。C新手:在數組中存儲結構

我收到以下錯誤,當我嘗試編譯我的代碼:

Queue.c: In function 'Enqueue': 
Queue.c:23: warning: assignment from incompatible pointer type 

這裏是我的代碼,如果需要的話我會提供頭部代碼:

#include "QueueElement.h" 
#include "Queue.h" 

#define QUEUE_SIZE 10 

struct QueueStruct { 
     QueueElement *contents[QUEUE_SIZE]; 
     int size; 
}; 

Queue CreateQueue(void) { 
     Queue q = malloc(sizeof(struct QueueStruct)); 
     q->size = 0; 
     return q; 
} 

void DestroyQueue(Queue q) { 
     free(q); 
} 

void Enqueue(Queue q, QueueElement *e) { 
     if (q->size < QUEUE_SIZE) { 

       q->contents[q->size++] = *e;  /* PROBLEM IS HERE */ 

     } 
} 

任何幫助不勝感激的問題以及其他任何建議。 謝謝你們。

+1

這似乎是深奧的指針符號用法。您試圖引用e,因此將e(它是幾乎任何大小的連續內存塊)的值複製到指針(通常是4個字節)。事情並不適合,即使大小匹配,「QueueElement」與「QueueElement *」不同。 – Trinidad 2011-01-28 02:58:59

+0

什麼是「隊列」?您提供的代碼中沒有「隊列」的定義。 – AnT 2011-01-28 03:03:25

回答

3

我相信q->contents[q->size++] = *e;應該只是q->contents[q->size++] = e;

*將指針解引用到內存位置的實際值,我不認爲你需要這個 - 你需要指針。

4

我相信你的意思是

q->contents[q->size++] = e; 

(沒有星號) 因爲你指定類型QueueElement *的東西QueueElement * []數組。

,或者您可能能夠通過改變這個,而不是修復它 - 我的身影,你可能意味着這可能是接近: -

QueueElement contents[QUEUE_SIZE]; 

不知道這是有道理的/我就在所有。

2

*eQueueElement型和q->contents[q->size++]QueueElement*

您應前,可掉落*或內容聲明:

QueueElement contents[QUEUE_SIZE]; 

這取決於如果你想存儲指針或值。