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

Why are pointers to incomplete types allowed and not variables of incomplete types?

为什么以下是合法的:

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; };

所以你 forward-declaring 一个 structtypedef 并在稍后定义它。非常好。

现在第二个例子:

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 定义后声明它按预期工作。

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

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