我得到“从不兼容的指针类型‘ListNode *’对‘struct ListNode *’的赋值”,即使我声明了 `typedef struct { … } ListNode;`

问题描述 投票:0回答:2

我正在尝试使用 C 创建一个链接列表,当我尝试编译它时,我不断收到此错误,

warning: assignment to ‘struct ListNode *’ from incompatible pointer type ‘ListNode *’ [-Wincompatible-pointer-types]

这些是我的结构:

typedef struct {
    void* data;
    struct ListNode* next;
    struct ListNode* prev;
} ListNode;

typedef struct {
    ListNode* head;
    ListNode* tail;
    int size;
} LinkedList;

完整的警告列表如下所示:

linkedList.c:26:21: warning: assignment to ‘struct ListNode *’ from incompatible pointer type ‘ListNode *’ [-Wincompatible-pointer-types]
   26 |         newNd->next = list->head;
      |                     ^
linkedList.c: In function ‘printList’:
linkedList.c:47:16: warning: assignment to ‘ListNode *’ from incompatible pointer type ‘struct ListNode *’ [-Wincompatible-pointer-types]
   47 |         currNd = currNd->next;
      |                ^
linkedList.c: In function ‘removeStart’:
linkedList.c:59:16: warning: assignment to ‘ListNode *’ from incompatible pointer type ‘struct ListNode *’ [-Wincompatible-pointer-types]
   59 |     list->head = temp->next;
      |                ^
linkedList.c: In function ‘insertLast’:
linkedList.c:88:18: warning: assignment to ‘ListNode *’ from incompatible pointer type ‘struct ListNode *’ [-Wincompatible-pointer-types]
   88 |             temp = temp->next;
      |                  ^
linkedList.c:90:20: warning: assignment to ‘struct ListNode *’ from incompatible pointer type ‘ListNode *’ [-Wincompatible-pointer-types]
   90 |         temp->next = newNd;
      |                    ^
linkedList.c: In function ‘removeLast’:
linkedList.c:109:14: warning: assignment to ‘ListNode *’ from incompatible pointer type ‘struct ListNode *’ [-Wincompatible-pointer-types]
  109 |         curr = curr->next;
      |              ^

如果需要更多信息,我很乐意添加更多信息。

c struct linked-list
2个回答
1
投票

在定义 ListNode 时,您创建了一个匿名结构的 typedef。因此它与 struct ListNode 不同。你需要做的是

typedef 结构ListNode { …… } 列表节点;


0
投票

如果您希望将指向结构的指针作为该结构的成员,则它需要在 typedef 之前有一个名称。

typedef struct ListNode { void* data; struct ListNode* next; struct ListNode* prev; } ListNode;
或者,从类型定义开始:

typedef struct ListNode ListNode; struct ListNode { void* data; ListNode* next; ListNode* prev; };
您的结构类型定义为 

LinkedList

 不需要这个,因为它不包含指向 
LinkedList
 作为成员的指针。

© www.soinside.com 2019 - 2024. All rights reserved.