Xref: utzoo comp.lang.c:14149 comp.lang.c++:2016 Path: utzoo!attcan!uunet!seismo!sundc!pitstop!sun!amdcad!ames!haven!uvaarpa!mcnc!rti!xyzzy!throopw From: throopw@xyzzy.UUCP (Wayne A. Throop) Newsgroups: comp.lang.c,comp.lang.c++ Subject: Re: Something new for C? Summary: offsetof() Keywords: offset of vars within structures Message-ID: <1838@xyzzy.UUCP> Date: 16 Nov 88 19:01:03 GMT References: <73@dsoft.UUCP> <481@njsmu.UUCP> Organization: Data General, RTP NC. Lines: 28 > klg@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 !mcnc!rti!xyzzy!throopw