offsetof() macro

Doug Gwyn gwyn at smoke.BRL.MIL
Mon Aug 28 13:44:06 AEST 1989


In article <1629 at cbnewsl.ATT.COM> dfp at cbnewsl.ATT.COM (david.f.prosser) writes:
>	(size_t)(((char *)&(((_type_*)&X)->_member_))-((char *)&X))
>where in the last X is some predeclared static object address.
>None of these are portable.

But this last one is pretty close, if X is changed to __X and made
an extern struct { double __d; char __pad[__UMPTEEN]; } __X; which has
probably pessimal alignment constraints (you could change the double to
a fancy union to make sure).  The Standard allows pointers to tough
alignments to be converted to pointers to easy alignments without problem.
The only practical problem remaining would be if the offset to the member
exceeded the valid pointer range for the __X object and if this mattered
(as it might, on a segmented architecture); if you make __UMPTEEN big
enough this problem could be avoided, at the cost of wasted data space.
(Perhaps the space could hold genuine C library data objects, with __X
just an entry point labeling the beginning of the data space.)



More information about the Comp.lang.c mailing list