Taking address of array

Steve Watt steve at wattres.uucp
Sat Apr 13 15:05:21 AEST 1991


In article <wolfram.671457523 at cip-s08> wolfram at cip-s08.informatik.rwth-aachen.de (Wolfram Roesler) writes:
>graham at tcom.stc.co.uk (Graham Bardsley) writes:
>
>>struct small_struct
>>{
>>	int x;
>>	char y[100];
>>};
>
>>What I want to know is, if the macro calculates:
>
>>((int) (((char *) (&(((s*) 0)->y))) - ((char *) 0)))
>
>>Is the value of this a valid construct which will calculate the offset of y on 
>>most traditional C compilers?
[ slurp! ]
>element e in struct s, you will have to write a new macro

>	#define aoffset(s,e) (int) ((((s*)0)->e) - 0)
>                                    ^
>				    '&' omitted
[ and use this slightly different macro on the array elements ]

Ick.

My much preferred method is to simply say [0] in the invocation of the
macro:

#define offsetof(t,e)  ((size_t)(&(((s) *)0)->e))   /* probably over-parened */

char *p = buf + offsetof(myType, arrayStructMember[0]);
                                                  ^^^
Seems cleaner than having a *slightly* different macro, and also reminds you
that this element is *somewhat* special, but if you change it later, the
compiler is more likely to yell at you.
-- 
Steve Watt       steve at wattres.UUCP                  swatt at IBM.COM
          ...!decwrl!gigo!wattres!steve    ...!apple!claris!wattres!steve
Never trust a computer bigger than you can lift.



More information about the Comp.lang.c mailing list