1

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

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;<<< 这是我收到错误消息的地方,到这里它工作正常

4

3 回答 3

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;
于 2020-06-01T11:56:16.820 回答
1

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

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

于 2020-06-01T11:58:01.113 回答
0
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 结构与结构定义

于 2020-06-01T12:08:18.290 回答