I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.
IE: given
struct mstct { int myfield; int myfield2; };
I could write:
mstct thing; printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing));
And get offset 4
for the output. How can I do it without that mstct thing
declaration/allocating one?
I know that &<struct>
does not always point at the first byte of the first field of the structure, I can account for that later.
Description. The C library macro offsetof(type, member-designator) results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type.
Use offsetof() to find the offset from the start of z or from the start of x . #include <stddef. h> size_t offsetof(type, member); offsetof() returns the offset of the field member from the start of the structure type.
How about the standard offsetof() macro (in stddef.h)?
Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like:
#define OFFSETOF(type, field) ((unsigned long) &(((type *) 0)->field))
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