Taking address of array
Stephen Clamage
steve at taumet.com
Fri Apr 12 00:48:15 AEST 1991
graham at tcom.stc.co.uk (Graham Bardsley) writes:
>struct small_struct { int x; char y[100]; };
>((int) (((char *) (&(((struct small_struct*) 0)->y))) - ((char *) 0)))
>Is the value of this a valid construct which will calculate the offset of y on
>most traditional C compilers...
The cast to char* and subtraction of zero don't do anything useful.
Casting the result to int is not appropriate on all systems. ANSI uses
a defined type called 'size_t', which is the unsigned integral type of
the 'sizeof' operator (usually unsigned int, sometimes unsigned long).
A typical 'offsetof' macro looks like this:
#define offsetof(type, field) ((size_t)&(((type*)0)->field))
This, like your example, is not portable to all systems, since some will
object to what appears to be a dereference of a null pointer.
Your best bet might be to put something like this in common header:
#if __STDC__
#include <stddef.h> /* ANSI C compiler, get correct size_t and offsetof */
#else
typedef unsigned int size_t; /* or whatever type is correct */
#define offsetof(type, field) ((size_t)&(((type*)0)->field))
#endif
--
Steve Clamage, TauMetric Corp, steve at taumet.com
More information about the Comp.lang.c
mailing list