我用 C 编写了一个小代码,其中定义了两个结构类型,它们在定义中具有彼此的成员。情况 1:如果在 struct bar 之前定义了 struct foo,则代码按预期编译。情况 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);
}
最佳答案
前向声明只通知编译器有一个叫做 foo
的东西,它对大小没有任何说明。
你可以使用 foo*
因为这是一个已知大小的指针而不是 foo
本身,因为大小是未知的,所以编译器不知道 的内存布局>bar
应该看起来像。
并且编译器只对您的文档进行一次遍历。所以它无法知道前面定义的结构。
关于c - 为什么结构的前向声明不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24055816/