C/CPP 怎么知道在结构节点还没有定义的情况下指向"next" 结构节点呢?

How does C/CPP know how to point to "next" struct node when the struct node is not yet defined?

创建单向链表时,通常创建一个Node结构如下:

struct node { 
    int data; 
    struct node *next; 
} 

但是,我想知道如果 node 的定义还没有完成,指向下一个节点 next 的指针如何知道结构 node 是什么。

我从 quora 了解到编译器无法编译以下内容:

struct node { 
    int data; 
    struct node next; 
}; 

出现以下错误:

a.c:6:13: error: field has incomplete type 'struct node' 
struct node next; 
            ^ 
a.c:4:8: note: definition of 'struct node' is not complete until the closing '}' 
struct node { 
       ^ 
1 error generated. 

如果node struct 的定义在使用'}'之前没有完成,那么我们怎么能将指针设置为未定义的用户定义数据类型node

因为 next 是指向 node 指针 ,编译成功不需要类型完整。

再考虑一个 C++ 中的简单示例。 A 的类型不需要完整,以便在结构 B 中有一个指向它的指针。准备好看到这个模式用于解决循环依赖。

struct A;

struct B {
    A *c;
};

struct A {
    B *d;
};

请注意,C 和 C++ 是两种截然不同的编程语言,虽然特定的 C 代码块 可能 是有效的 C++,但不能保证它 将是,或者即使是,它将以完全相同的语义表现。

不需要知道。指针只是一个地址。在您的结构中,当您定义下一个属性时,编译器将在结构中保留足够的 space 以保留地址。它不需要知道完整的结构。

这个:

struct node { 
    int data; 
    struct node next; 
};

无法编译,因为编译器无法确定节点结构的大小。结构的大小等于结构的大小加上 int 的大小。