【问题标题】:error: dereferencing pointer to incomplete type - C language错误:取消引用指向不完整类型的指针 - C 语言
【发布时间】:2020-06-01 11:44:04
【问题描述】:

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

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;

【问题讨论】:

  • struct Node 不是 Node
  • 我使用完全相同的不同功能,效果很好。我用了Node * p = list->head;,一切都很好。

标签: c struct declaration typedef definition


【解决方案1】:

在这个结构的typedef声明中

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

struct Node 类型是不完整的类型。也就是类型名struct Node被引入但未定义。

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

很明显你的意思是以下

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

【讨论】:

  • 谢谢,你解释得很好。
【解决方案2】:

错误:取消引用指向不完整类型的指针

这意味着编译器无法在您进行访问的翻译单元中找到该结构的定义 - 它只能找到一个声明。事实证明,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 结构标签实际上存在于不同的命名空间中,但这是无需考虑的事情之一 - 只需要做。)

【讨论】:

    【解决方案3】:
    struct Node * next;
    

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

    typedef struct {
       ...
    } Node;
    

    Node 是结构定义的 typedef。它不等于struct Node


    提供结构标签Node:

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

    您的代码运行良好。


    也可以看看这里:

    typedef struct vs struct definitions

    【讨论】:

      猜你喜欢
      • 2018-05-31
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      相关资源
      最近更新 更多