Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c Subject: Re: Taking address of array Message-ID: <666@taumet.com> Date: 11 Apr 91 14:48:15 GMT References: <1991Apr9.172534.28982@tcom.stc.co.uk> Organization: Taumetric Corporation, San Diego Lines: 32 graham@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 /* 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@taumet.com