2016-12-14 69 views
1
int main(void) 
{ 
    struct a 
    { 
     struct b* x; 
    }; 
} 

我定義struct a爲包含指針xstruct b而不定義struct b。我期待着一個錯誤。即使通過包含-Wall,我也沒有從編譯器中得到什麼。有沒有對此的解釋?爲什麼一個結構體中可能包含一個指向未定義的另一個結構體的指針?

+0

它知道如何做指針。但是你不能在不定義'struct b'的情況下解引用它('* x')。 – e0k

+0

在上下文中,'struct b'是一個不完整或不透明的類型。他們其實很有用。 –

回答

2

這只是一種標準的語言功能。 struct b現在是一個不完整的類型。用不完整的類型可以做很多事情。但有一點可以做的是聲明不完整類型的指針。

您將可以通過提供完整聲明struct b來完成該類型。之後它將成爲一個普通的結構類型。

+0

當我刪除'*',我得到了'錯誤:字段'x'有不完整的類型'。這是否意味着包含不完整類型是非法的,但是包含指向不完整類型的指針是合法的?這怎麼可能有用? –

+0

@W。朱:是的,聲明不完整類型的指針是合法的,但是聲明不完整類型的對象是非法的。它對於許多不同的目的非常有用,比如實現隱藏(不透明類型)。事實上,不依賴這個特性就不可能聲明一個簡單的鏈表。再次,請記住,不完整類型稍後會在完全聲明時(以及在何處)變爲完整類型。 – AnT

2

你有什麼是incomplete type,這樣的類型的指針是完全正確的,但除非你完成它否則不能實例化。

2.7 Incomplete Types

You can define structures, unions, and enumerations without listing their members (or values, in the case of enumerations). Doing so results in an incomplete type. You can’t declare variables of incomplete types, but you can work with pointers to those types.

struct point; 

At some time later in your program you will want to complete the type. You do this by defining it as you usually would:

struct point { 
    int x, y; 
}; 

This technique is commonly used to for linked lists:

struct singly_linked_list { 
    struct singly_linked_list *next; 
    int x; 
    /* other members here perhaps */ 
}; 
struct singly_linked_list *list_head; 
+0

是否意味着'struct a'包含一個指向空結構的指針? –

+0

@ W.Zhu。對不起,前面的答案,看我更新的答案 – smac89

0

因爲編譯器分配結構,因爲它知道一個指針的大小,但你不能使用x因爲編譯器將不知道如何取消引用指針除非有結構的定義。

您可以通過使用前置聲明利用這一點,你可以聲明一個未知struct類型的指針和避免包括僅從而改善編譯時間和精力結構的可能大的頭文件。

相關問題