offsetof (was: Re: Something new for C?)

Jim Shankland jas at ernie.Berkeley.EDU
Thu Nov 10 02:54:40 AEST 1988


In article <481 at njsmu.UUCP> klg at njsmu.UUCP (Kenneth Goodwin) writes:
>Until they actually stick something like [offsetof] into the compiler, try
>this:
>
>#define	offsetof(Struct, Member)	(&((struct Struct *)0)->Member)
>
>...
>
>	Since all kludges have an inherent risk of non-portability
>	comments on the above method are welcome.

Alas, I've run into C compilers on a few UNIX machines that barf on this.
Not about the syntax itself -- they just don't want you dereferencing
the null pointer (even though you're not, really).  Which means that for
maximal portability, this won't work either.

On such machines, you must have an instance of the structure:

struct mumble foo;
int mem_offset = (char *)(&foo.member) - (char *)(&foo);

Sigh.  The things you have to put up with in the portability trenches.
This is about the 10,000th reason that we need ANSI C *now*.

Jim Shankland
jas at ernie.berkeley.edu



More information about the Comp.lang.c mailing list