The C standard does not provide casting for structures and does not define the reinterpretation via pointer conversion shown in the question. (Certain such reinterpretations are supported for combinations of types specified in C 2018 6.5 7, but not for standalone structures.) The standard provides two other ways to reinterpret objects as another type.
First, one may simply copy the bytes of one object into another:
_Static_assert(sizeof a == sizeof b, "a and b must be the same size.");
memcpy(&b, &a, sizeof b);
For small objects, a good compiler with optimization enabled is likely to elide the copy and interpret the data in the new type directly from the memory or register(s) where it already is.
Second, one may store to one union member and read through another (C 2018 6.5.2.3 3, and see footnote 99):
_Static_assert(sizeof a == sizeof b, "a and b must be the same size.");
b = (union { struct s1 s1; struct s2 s2; }) {a} .s2;
The union type in parentheses starts a compound literal. The {a}
gives a
as an initial value for the union, specifically for the s1
member. Then .s2
accesses the s2
member.
Note that although the _Static_assert
is included for some safety, you must also ensure the structure layouts are compatible for your purposes.