Possible Duplicate:
Why does this C code work?
How do you use offsetof() on a struct?
I read about this offsetof macro on the Internet, but it doesn’t explain what it is used for.
#define offsetof(a,b) ((int)(&(((a*)(0))->b)))
What is it trying to do and what is the advantage of using it?
It has no advantages and should not be used, since it invokes undefined behavior (and uses the wrong type –
intinstead ofsize_t).The C standard defines an
offsetofmacro instddef.hwhich actually works, for cases where you need the offset of an element in a structure, such as:which would let you programmatically fill the fields of a
struct fooby name, e.g. when reading a JSON file.