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

时间:2017-01-19 20:52:25

标签: c typedef forward-declaration

为什么以下是合法的:

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 ++,这个问题的答案是否相同?

2 个答案:

答案 0 :(得分:3)

这就是这样:

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

与:

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

因此,您正在向前声明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定义后声明它按预期工作。

答案 1 :(得分:3)

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

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

相关问题