为什么这个强制转换编译失败?
问题描述:
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具有相同类型的成员,为什么此强制转换失败?为什么这个强制转换编译失败?
谢谢
答
在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是指向
答
你不能投了struct
一样,在C.使用memcpy
如果你真的需要a1
复制到b1
。
memcpy(&b1, &a1, sizeof(a1));
这会工作。用适当的'(struct BBB *)'强制转换。 – RedX