为什么结构体的前向声明不起作用?

anu*_*amb 2 c struct forward-declaration

我用 C 编写了一个小代码,其中定义了两个结构类型,它们在定义中具有彼此的成员。情况 1:如果 struct foo 在 struct bar 之前定义,则代码按预期编译。情况 2:如果 struct foo 在 struct bar 之后定义,它将不会编译,这也是预期的,因为无法知道 struct foo 变量的内存要求。但是我期待如果在情况 2 中使用 struct foo 的前向声明它会编译。但它不起作用。我错过了什么?

#include<stdio.h>
#include<stdlib.h>

struct foo; // forward declaration

struct bar
{
  int a;
  struct bar *next;
  struct foo ch;
};

struct foo
{
  struct bar *n;
  struct foo *nx;
};


int main()
{
  struct bar p;
  return(0);
}
Run Code Online (Sandbox Code Playgroud)

vla*_*sch 6

前向声明只通知编译器有被调用的东西,foo它对大小没有任何说明。您可以使用,foo*因为这是一个已知大小的指针而不是foo它本身,因为大小是未知的,所以编译器不知道它的内存布局bar应该是什么样子。

并且编译器只对您的文档进行一次传递。所以它无法知道前面定义的结构。