error: dereferencing pointer to incomplete type - C language

error: dereferencing pointer to incomplete type - C language

前几天做了一个功能,效果不错。这是我使用的结构定义。

typedef struct {
    int data;
    struct Node * next;
} Node;

typedef struct {
    Node * head;
    Node * current;
    int size;
} List;

那我就有这个功能了

void returnMiddle(List * list){
    Node * first = list->head;
    Node * second = list->head;

    if(list->head != NULL){
        while(second != NULL && second->next != NULL){
            first = first->next;
            second = first->next->next; 
        }
        printf("Middle is: %d", first->data);
    }
}

但现在我收到错误消息,我不明白为什么?有人知道吗?

second = first->next->next; <<< 这是我收到错误消息的地方,到这里它工作正常

在这个结构体的 typedef 声明中

typedef struct {
    int data;
    struct Node * next;
} Node;

类型 struct Node 是不完整的类型。即引入了类型名struct Node但未定义

注意typedef name Node 和type name struct Node 命名两个不同的实体。名称 Node 命名一个未命名的结构,而 struct Node 命名一个尚未定义的结构。

很明显你的意思是下面的

typedef struct Node {
    int data;
    struct Node * next;
} Node;

error: dereferencing pointer to incomplete type

这意味着编译器无法在您进行访问的翻译单元中找到该结构的定义 - 它只能找到一个声明。事实证明,struct Node * next; 是一个指向先前未在声明时定义的类型的指针。因为它仅在编译器到达结构的 }; 时才定义。

对于自引用结构,您需要前向声明类型才能将其用作结构成员。根据您的编码风格,这意味着:

typedef struct Node Node;

struct Node {
    int data;
    struct Node* next;  // also possible: Node* next;
};

typedef struct Node {
    int data;
    struct Node* next; 
} Node;

(类型 Node 和结构标签 Node 实际上存在于不同的命名空间中,但这是不需要考虑的事情之一 - 只需考虑即可。)

struct Node * next;

struct Node 是对结构 Node 的前向声明,但您尚未定义名为 Node 的结构 - 意味着 struct Node 是一个不完整的类型。

typedef struct {
   ...
} Node;

Node 是结构定义的类型定义。它不等于 struct Node.


提供结构标签Node:

typedef struct Node {
    int data;
    struct Node * next;
} Node;

并且您的代码工作正常。


也可以看看这里:

typedef struct vs struct definitions