Taking address of array

Chris Torek torek at elf.ee.lbl.gov
Fri Apr 12 20:45:20 AEST 1991


(this is all the result of X11 making a heroic effort to define `offsetof'
without using the ANSI `offsetof', even though the ANSI `offsetof' exists
precisely because it is not possible to define a portable `offsetof'...)

Given the X11R4 offsetof `approximation' macro
  #define offsetof(s, e) ((int)((char *)&((s *)0)->e - (char *)0))
(spelling mine---I took out all the `unnecessary' parentheses, and may
have changed the name itself [I prefer the ANSI `offsetof' name, since
people have to know what it means, these days]),

>In article <1991Apr9.172534.28982 at tcom.stc.co.uk> graham at tcom.stc.co.uk
>(Graham Bardsley) writes:
>>struct small_struct {
>>	int x;
>>	char y[100];
>>};
>>[`offsetof(struct small_struct, y)' produces] the warning: 
>>	& before array or function: ignored

This simply means that you do not have an ANSI-conformant compiler
(no surprise, or you would not have to `make up' a nonportable offsetof
approximation---the X11 definition is the best one comp.lang.c has ever
seen, despite some previous article's advice to drop the `char *' casts
and the subtraction of `(char *)0').

In article <MARC.91Apr11082924 at marc.watson.ibm.com>
marc at watson.ibm.com (Marc Auslander) writes:
>The Risc System/6000 compiler also issues a warning message and compiles.  

Sheesh, you guys are still shipping non-ANSI compilers? :-)

(Seriously, this particular glitch is trivial to fix in PCC, and probably
in most compilers: to allow &array you simply REMOVE one or two lines.
Everything else already works.  The compiler has to go out of its way
to reject &array.)

>Note that if you have a macro which takes addresses of things and you
>need to pass it an array, a work around is to pass the first element.

This will in fact always work wherever offsetof() works at all: the C
language effectively guarantees that

	offsetof(struct small_struct, y)

and

	offsetof(struct small_struct, y[0])

will produce the same value (provided this offsetof() works at all).

> ((int) (((char *) (&(((struct small_struct*) 0)->y[0]))) - ((char *) 0)))
>
>is correct C.

Correct syntactically, but its meaning is up to the compiler---that is why
offsetof() is not portable.
-- 
In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 415 486 5427)
Berkeley, CA		Domain:	torek at ee.lbl.gov



More information about the Comp.lang.c mailing list