structure element offsets

rbutterworth at watmath.UUCP rbutterworth at watmath.UUCP
Fri Nov 28 06:05:23 AEST 1986


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.

This macro produces a POINTER.
I believe that what was requested was an INTEGER byte offset.

What you have to do is take the pointer produced above,
cast it into some generic type pointer (e.g. (char*)),
and subtract from it another generic pointer to the beginning
of the structure.  The difference of two pointers of the same
type is then an integral type, and in this case produces a
somewhat more realistic value of 4.

  (   ((char*)(&(((Str*)0)->f2)))
    - ((char*)((Str*)0))
  )



More information about the Comp.lang.c mailing list