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

标签 c struct forward-declaration

我用 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/

相关文章:

c++ - 在自己的声明中使用类作为模板参数

c - 如何让光标向后移动1行

c++ - 创建哈希表来存储某个指针的值

c - 查找二维数组中特定元素的总数

c - 为什么 sizeof unsigned char array[10] 是 10

c++ - 错误 : Invalid use of incomplete type struct Subject; error: forward declaration of struct Subject

c - 将结构传递给 c 中的函数

struct - 使用单元结构的真实示例是什么?

c - 在 C 中,结构名称何时必须包含在结构初始化和定义中?

c++ - 为什么我不能在 C++ 的限定命名空间中转发声明类型?