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

前提是你 提交于 2020-01-05 05:56:19

问题


Why is the following legal:

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

and the following illegal:

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.

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


回答1:


This of it this way:

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

is the same as:

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

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

Now the second example:

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

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.




回答2:


You are allowed to create pointers to incomplete types, because the size of the pointer object does not depend on the size of the pointed-to type. Pointers to different struct types have the same size and representation, regardless of the size of the struct type itself.

You are not allowed to create instances of incomplete types, since the size of the type isn't known.



来源:https://stackoverflow.com/questions/41751479/why-are-pointers-to-incomplete-types-allowed-and-not-variables-of-incomplete-typ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!