A fairly simple question (I hope). Given a struct in C (the layout of which is known at compile time), is there a way (via macro, or other) that I can access the byte position of a named field in the struct?
Support for unions would be a bonus. The compiler is VC++ 2008. Assume that #pragma pack(1)
is used.
Cheers
You're looking for offsetof
. It should be in stddef.h
, but in case you don't have that, a sample implementation (from wikipedia):
#define offsetof(st, m) \
((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))
For a union, the offset of every field is 0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With