structure element offsets

Karl Heuer karl at haddock.UUCP
Fri Dec 5 11:42:53 AEST 1986


In article <720 at dg_rtp.UUCP> throopw at dg_rtp.UUCP (Wayne Throop) writes:
>>bader at spice.cs.cmu.edu (Miles Bader) writes:
>>> Is there any way of finding the offset of a structure element from
>>> the beginning of a structure in a portable AND efficient way?

>stuart at bms-at.UUCP (Stuart D. Gathman) writes:
>> #define spos(s,m)	((char *)&((struct s *)0)->m - (char *)0)
>
>... A couple of points remain.  First, there is no guarantee that pointer
>arithmetic or offset calculations will work for the null pointer.

Note also that the result might not be a legal constant.

However, ANSI seems to have its collective heart set on making offsetof()
part of the standard, which means that on machines where the above construct
doesn't work, *some* hook must be allowed -- even if the implementor has to
make "offsetof" a builtin operator instead of a macro.

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint
(Btw, "sposa(s,m)" is redundant since "spos(s,m[0])" will do, and the macro
would be more useful if the word "struct" were omitted.)



More information about the Comp.lang.c mailing list