Something new for C?

Wayne A. Throop throopw at xyzzy.UUCP
Thu Nov 17 05:01:03 AEST 1988


> klg at njsmu.UUCP (Kenneth Goodwin)
> Until they actually stick [...offsetof...] into the compiler , try this:
>
> #define offsetof(Struct, Member) (&((struct Struct *)0)->Member)
>
> comments on the above method are welcome.

Well, the type of the resulting expression is an address, not an
integer offset in bytes, which is what I suppose is intended.  Casting
the above to int or unsigned isn't much help either, on word-oriented
machines.  So, there are two possible expressions involving addressing
from the null pointer that are superior:

    #define offsetof(S,M) ((int)(char*)&(((struct Struct *)0)->M))

or, somewhat better

    #define offsetof(S,M) (((char*)&(((struct S)0)->M))-((char*)0))

The only way to improve on these (that I know of) in terms of
portability is to actually allocate an example of S, and that can't be
done purely from a macro.

--
"Please, spare me, have mercy!"
"Yes, that's it, beg, grovel.  Now offer me riches, power, position."
                                        --- from "The Princess Bride"
-- 
Wayne Throop      <the-known-world>!mcnc!rti!xyzzy!throopw



More information about the Comp.lang.c mailing list