[英]Why am i getting “warning: assignment from incompatible pointer type”? Double linked list in a struct array
[英]Warning: assignment from incompatible pointer type in linked list struct
我收到很多“來自不兼容指針類型的賦值”警告,但我不知道為什么。 警告出現在此部分中:
void addNode(linkedList* list, int board)
{
Node* newNode = createNode(board);
(list->last)->next = newNode; // this line has warning
newNode->prev = list->last; // this line has warning
}
結構和其余代碼為:
typedef struct{
int board;
struct Node* next;
struct Node* prev;
}Node;
typedef struct{
int length;
Node* first;
Node* last;
}linkedList;
Node* createNode(int board)
{
Node* node = (Node*)malloc(sizeof(Node));
node->next = NULL;
node->prev = NULL;
node->board = board;
return node;
}
linkedList* createList()
{
linkedList* list = (linkedList*)malloc(sizeof(linkedList));
list->first = NULL;
list->last = NULL;
list->length = 0;
return list;
}
這個 ...
typedef struct{ int board; struct Node* next; struct Node* prev; }Node;
...聲明無標簽結構類型,並將Node
定義為該類型的別名。 它沒有定義類型struct Node
到其成員next
和prev
點。 這不會阻止聲明指向此類的指針,但是該類型與Node
,並且與之不兼容。
假設其他地方沒有struct Node
定義,最簡單的解決方案是僅添加該標記:
typedef struct Node {
int board;
struct Node* next;
struct Node* prev;
}Node;
那給您您肯定地意味。
還要注意,您根本就不需要typedef
。 添加標簽后,您可以在任何地方將該類型稱為struct Node
。 typedef
別名只是一種方便,我認為這種用法已被過度使用。 通常, typedef
它們的混淆超過了他們的幫助。
您實際上從未定義struct Node
。
您將別名( typedef
)指定為Node
是未標記的struct
。 當您稍后聲明指針struct Node*
,編譯器允許它作為指向不完整類型(隱式聲明)的指針,但這與程序中聲明的任何類型都不相同。
使用自引用指針聲明結構的一種好方法是:
typedef struct Node Node;
struct Node {
int board;
Node* next;
Node* prev;
};
在這種表述中,第一行將Node
定義為仍不完整的類型struct Node
的別名,然后由第二個聲明定義。 遇到Node*
成員聲明時, struct Node
仍不完整,但是允許使用指向不完整類型的指針。
我喜歡這種樣式的原因之一是,它與struct
是一種不透明的數據類型(其成員不適合公共使用)的常見情況很好地兼容。 在那種情況下,可以將typedef
放在頭文件中,從而允許將不透明類型的指針用於函數原型或用作局部變量。 然后, struct
定義本身進入實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.