2011-10-12 37 views
2
struct AAA 
{ 
    char a_1; 
    int a_2; 
}; 

struct BBB 
{ 
    char b_1; 
    int b_2; 
}; 


int main(void) 
{ 
    struct AAA a1 = {2, 4}; 
    struct BBB b1; 
    b1 = (struct BBB)a1; 
    return 0; 
} 

如上圖所示,「B1 =(結構BBB)A1;」所作的complie說 「錯誤:轉換所請求的非標量類型」。 結構AAA和結構BBB具有相同類型的成員,爲什麼此強制轉換失敗?爲什麼這個強制轉換編譯失敗?

謝謝

+0

這會工作。用適當的'(struct BBB *)'強制轉換。 – RedX

回答

5

在C標準(在N1256看,因爲它是免費提供的)

6.5.4定義角色的運營商。

6.5.4.2列表作爲限制性上轉換操作符:

Unless the type name specifies a void type, the type name shall specify qualified or unqualified scalar type and the operand shall have scalar type.

6.2.5.21描述標量和聚合類型爲:

Arithmetic types and pointer types are collectively called scalar types. Array and structure types are collectively called aggregate types.37)

的結構類型是明確因此不是標類型,這意味着不符合演員操作符的約束。因此,代碼失敗。如果A1和B1是指向

6

你不能投了struct一樣,在C.使用memcpy如果你真的需要a1複製到b1

memcpy(&b1, &a1, sizeof(a1));