簡體   English   中英

為什么允許指向不完整類型的指針,而不允許不完整類型的變量?

[英]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; };

所以,你向前聲明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之后進行聲明可以按預期工作。

您可以創建指向不完整類型的指針,因為指針對象的大小不取決於指向類型的大小。 指向不同struct類型的指針具有相同的大小和表示形式,而不管struct類型本身的大小如何。

不允許創建不完整類型的實例 ,因為類型的大小未知。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM