2012-10-23 63 views
0

我有以下結構:聯盟結構錯誤

struct type1 { 
    struct type2 *node; 
    union element { 
     struct type3 *e; 
     int val; 
    }; 
}; 

當初始化一個指針*f指向的type1一個實例,做這樣的事情: f.element->e甚至只是f.element,我得到:

error: request for member ‘element’ in something not a structure or union 

我在這裏監督什麼?

+0

你能告訴'F'的聲明?也許你的意思是'f-> element.e'? – cyco130

+2

'element'是聯合標記,而不是成員名稱。嘗試使用'struct {... union元素{...} elem; };'和'f.elem'。 –

+0

@ cyco130同樣的錯誤。 – darksky

回答

3

element是工會的名稱,而不是type1的成員的名稱。你必須給union element名稱:

struct type1 { 
struct type2 *node; 
    union element { 
     struct type3 *e; 
     int val; 
    } x; 
}; 

那麼你就可以訪問它:

struct type1 *f; 
f->x.e 
+0

也許你應該爲你的'f'使用malloc內存? – halex

+0

'f'必須以某種方式初始化,是的。 –

+1

這裏可能有一些C版本的問題。 C 2011推出了匿名結構和聯盟,在這種情況下'f-> e'將與原始聲明一起工作。但是,如果Darksky使用早期版本的C,則必須修改聯合聲明,如此答案中所示。 –

-1

如果f是一個指針,那麼你可以使用F-訪問「元素」>元素,或(* F).element

更新:剛纔看到「元素」是工會的名稱,而不是一個成員的結構。 您可以嘗試

union element { 
    struct type3 *e; 
    int val; 
} element; 

所以最終的結構是這樣的:

struct type1 { 
    struct type2 *node; 
    union element { 
     struct type3 *e; 
     int val; 
    } element; 
}; 

現在你可以訪問元素成員這樣,通過TYPE1 * F:

struct type1 *f; 

// assign f somewhere 

f->element.val; 
+0

請閱讀該問題。這就是我所做的,這就是我得到的錯誤。 – darksky

+1

@Darksky號你根據你的問題做了'f.element'和** not **'f-> element'。 – halex

+0

不,我**都做**。引用:'f.element-> e或甚至只是f.element,我會得到'。 – darksky