为什么允许指向不完整类型的指针而不是不完整类型的变量?

为什么以下是合法的:

typedef struct a aType; struct a { int x; aType *b; }; 

以下非法:

 void main() { typedef struct a aType; aType someVariable; struct a { int x; aType *b; }; } 

我只是好奇,因为在每种情况下它都是前向引用,据我所知,至少对于函数和变量,前向引用是不合法的。

另外,对于C ++,这个问题的答案是否相同?

这样就可以了:

 typedef struct a aType; struct a { int x; aType *b; }; 

是相同的:

 struct a; typedef struct a aType; struct a { int x; aType *b; }; 

所以你要向前声明一个struct ,输入它并稍后定义它。 非常好。

现在是第二个例子:

 typedef struct a aType; aType someVariable; struct a { int x; aType *b; }; 

这与它在本地范围内的事实无关。 发生了什么事:

 struct a; typedef struct a aType; aType someVariable; // error: when it gets here, aType is still incomplete struct a { int x; aType *b; }; aType someVariable; // perfectly fine, aType not incomplete 

请记住,编译按顺序进行。 当你尝试声明someVariable ,编译器不知道它是什么struct a ,所以它不知道它的大小,因此它不知道要为它分配多少内存,因此编译错误。 在定义aType之后声明它按预期工作。

您可以创建指向不完整类型的指针,因为指针对象的大小不依赖于指向类型的大小。 无论struct类型本身的大小如何,指向不同struct类型的指针都具有相同的大小和表示。

您不能创建不完整类型的实例 ,因为类型的大小未知。