为什么允许指向不完整类型的指针而不是不完整类型的变量? [英] Why are pointers to incomplete types allowed and not variables of incomplete types?

查看:44
本文介绍了为什么允许指向不完整类型的指针而不是不完整类型的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下是合法的:

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

以及以下违法行为:

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

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

I'm just curious as in each case it is forward referencing and as far as I know, at least for functions and variables, forward referencing is not legal.

另外,C++ 的答案是否也一样?

Also, would the answer for this be the same for C++ as well?

推荐答案

就这样:

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

等同于:

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

所以你正向声明一个structtypedef然后定义它.完全没问题.

So you're forward-declaring a struct, typedefing it and later defining it. Perfectly fine.

现在是第二个例子:

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

这与它在本地范围内的事实无关.这是怎么回事:

This has nothing to do with the fact that it's in local scope. What's happening is this:

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 之后声明它按预期工作.

Remember that compilation happens in order. When you try to declare someVariable the compiler doesn't know what struct a is yet, so it doesn't know its size, hence it doesn't know how much memory to allocate for it, hence a compile error. Declaring it after aType is defined works as expected.

这篇关于为什么允许指向不完整类型的指针而不是不完整类型的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆