Is this type punning well defined?
struct result{
int a,b,c,d;
}
union convert {
int arr[4];
struct result res;
}
int arr1[4] = {1,2,3,5};
union convert *pointer = (union convert *) arr1;
(union convert *) arr1
risks alignment failure.
A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined. C11dr §6.3.2.3 8
There is no requirement that union convert
and int
share the same alignment. union convert
requirements may exceed int
for example.
Consider this possibility: arr1[]
lives on int
street where all addresses are multiple of 4. union
and struct
friends lives on "multiple of 8" street. arr1[]
might have address 0x1004 (not a multiple of 8).
In 2019, alignment failures are more commonly seen with char
(needing 1) and other types needing 2 or more. In OP's select case, I doubt a real platform will have alignment issues, yet incorrect alignment remains possible.
This type punning is not well defined.
Additional concerns
Other answers and comments discuss padding issues, which further identifies trouble.
@Eric Postpischil comment about improper access with pointer->res.a
adds more reasons to consider this UB.