开发者

why does this force conversion compile fail?

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;
}

as shown above, “b1 = (struct BBB)a1;” made the complie say "error: conversion to non-scalar type requested". the struct AAA and the struct BBB have the same type of members, why does this force co开发者_运维问答nversion fail?

thank you


You can't cast a struct like that in C. Use memcpy if you really need to copy a1 into b1.

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


In the C standard (looking at N1256 as it is freely available)

6.5.4 defines Cast operators.

6.5.4.2 lists as a restriction on cast operators:

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 describes scalar and aggregate types as:

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

A structure type is therefore definitively NOT a scalar type, which means the constraint on the cast operator is not met. Thus, the code fails.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜