structure element offsets

David Messer dave at viper.UUCP
Sat Nov 29 08:29:47 AEST 1986


In article <3622 at watmath.UUCP> rbutterworth at watmath.UUCP (Ray Butterworth) writes:
 >In article <768 at nike.UUCP>, hahn at fred (Jonathan Hahn) 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?
 >> Try:
 >> #define OFFSET(elem, type)    (&(((type *)0)->elem))
 >> This utilizes a pointer of address 0, for which the address of the
 >> element reference yeilds the offset of the element.
 >
 >typedef struct { int f1; int f2; } Str;
 >
 >I tried OFFSET(Str,f2) on my machine and got 262,144 (=01000000 =2^18).
 >That's a pretty big offset considering it only has to pass
 >over one int.
 >I won't mention what Lint had to say about it.
 
It could be because you used OFFSET(Str,f2) instead of the correct
OFFSET(f2,Str).  You got the parameters reversed.

A simpiler definition of the OFFSET macro is the following:

	#define OFFSET(mos)  ((long)(&(((char *)0)->mos)))

This will produce a proper offset on almost all machines.  (But
not all, some machines have different formats to pointers to
different types.  Also, this macro assumes that (long)((char *)0) == 0L.)
-- 
Disclaimer:                       | David Messer 
I'm always right and I never lie. | Software Consultant 
My company knows this and agrees  | UUCP:  ihnp4!quest!viper!dave 
with everything I say.            |        ihnp4!meccts!viper!dave



More information about the Comp.lang.c mailing list