c - sizeof anonymous nested struct -
suppose have structure i'm using model various packet formats:
#define maxpacket 20 typedef struct { u8 packetlength; union { u8 bytes[maxpacket]; struct { u16 field1; u16 field2; u16 field3; } format1; struct { double value1; double value2; } format2; }; } packet;
i can expect sizeof(packet)
21
. there way like:
sizeof(packet.format2)
? i've tried that, compiler not happy. obviously, pull format1
out separate typedef , sizeof(format1)
. i'm curious if have through of that. hierarchical composition of formats. gcc on 8bit processor.
i'm equally interested if there's way use nested type. if have lot of
apacketpointer->format2.value1; // not onerous, if nesting gets deeper...
then nice do:
packet.format2 *formatptr = &apacketpointer->format2; formatptr->value2; // etc
again, refactoring bunch of preceding typedefs solve problem, lose nice namespacing effect of nested dotted references.
for work in c90, can use macro modeled on toolchain's offsetof()
macro:
#define sizeof_field(s,m) (sizeof((((s*)0)->m)))
adjust accordingly if toolchain's offsetof()
macro isn't based on casting 0
pointer structure's type.
when use so:
std::cout << sizeof_field(packet,format1) << std::endl; std::cout << sizeof_field(packet,format2) << std::endl;
i output:
6 16
for second question, if you're willing rely on gcc's typeof
extension can create similar macro declaring pointers nested anonymous structs:
#define typeof_field(s,m) typeof(((s*)0)->m) ... typeof_field(packet,format2)* f2 = &foo.format2;
to honest, find construct pretty ugly, might still better other options have available.
gcc documents "operand of typeof evaluated side effects if , if expression of variably modified type or name of such type", apparent null pointer deference should not result in undefined behavior when variable length array not involved.
Comments
Post a Comment