c - Why is the offsetof macro necessary? -
i new c language , learned structs , pointers.
my question related offsetof
macro saw. know how works , logic behind that.
in <stddef.h>
file definition follows:
#define offsetof(type,member) ((unsigned long) &(((type*)0)->member))
my question is, if have struct shown below:
struct test { int field1: int field2: }; struct test var;
why cannot directly address of field2
as:
char * p = (char *)&var; char *addressoffield2 = p + sizeof(int);
rather writing this
field2offset = offsetof (struct test, field2);
and adding offset value var's starting address?
is there difference? using offsetof
more efficient?
the c compiler add padding bits or bytes between members of struct
in order improve efficiency , keep integers word-aligned (which in architectures required avoid bus errors , in architectures required avoid efficiency problems). example, in many compilers, if have struct
:
struct imlikelypadded { int x; char y; int z; };
you might find sizeof(struct imlikelypadded)
12, not 9, because compiler insert 3 padding bytes between end of one-byte char y
, word-sized int z
. why offsetof
useful - lets determine things factoring in padding bytes , highly portable.
Comments
Post a Comment