c - 警告 : assignment from incompatible pointer type in linked list struct

标签 c pointers doubly-linked-list

我收到很多“来自不兼容指针类型的赋值”警告,但我不知道为什么。 警告出现在这部分:

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定义为该类型的别名。它没有定义其成员nextprev指向的struct Node类型。这并不妨碍声明指向此类类型的指针,但该类型与 Node 不同,并且与其不兼容。

假设其他地方没有任何 struct Node 的定义,最简单的解决方案就是添加该标记:

typedef struct Node {
    int board;
    struct Node* next;
    struct Node* prev;
}Node;

这就是你的意思。

还要注意,您根本不需要 typedef。添加标签后,您可以在任何地方将该类型引用为struct Node。 typedef 的别名只是为了方便,我认为它被过度使用了。很多时候,typedef 带来的困惑多于其帮助。

关于c - 警告 : assignment from incompatible pointer type in linked list struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312010/

相关文章:

调用不带参数的函数,尽管它需要一个 [K&R-C]

c - 不同类型的单个 mmap 指针

c - 如何知道指针数组中指针的长度是多少?

C++ 成员函数指针

C - 从双向链表中删除任意节点

c - 找不到段错误

c - 加载链接列表文件指针

c - 如何在包含 char * 指针的结构**中存储动态字符串

java - 二叉搜索树中节点的路径作为二叉搜索树

c++ - (自定义)双向链表的第一个元素重复