"array" vs. "&array" ?

Andrew Koenig ark at alice.UUCP
Mon Jan 15 03:11:25 AEST 1990


In article <5260 at buengc.BU.EDU>, bph at buengc.BU.EDU (Blair P. Houghton) writes:

> Oh, and the solution, on all the compilers I can get ahold of
> (being an empiricist when it's efficacious) will accept and
> work as intended if we just replace the offending line with

> 	aptr = (type_t *) &a;

> Whether this is a hack in the compilers or a deliberate misreading
> of the std or ambiguously allowed by the std I don't know.

It's a hack.

Recall that this is in the context of

	type_t *aptr, a[MAXINDEX+1];

That is, `a' is an array of MAXINDEX+1 values of type `type_t' and
`aptr' is a pointer to a type_t.  Then `&a' is of type
`pointer to array of MAXINDEX+1 type_t', otherwise written
`type_t(*)[MAXINDEX+1]', and converting that to `type_t *' is
an unsafe cast.  Instead, in ANSI C, you can write

	aptr = *(&a);

which is, of course, precisely equivalent to

	aptr = a;

Here, you're dereferencing &a again to obtain the array itself,
which is then silently converted to a pointer to its initial element.

Another way to write this is:

	type_t (*array_ptr)[MAXINDEX+1] = &a;
	aptr = *array_ptr;

That is, declare an array pointer variable and explicitly store
the array pointer there, then dereference it and implicitly convert
it to an element pointer.
-- 
				--Andrew Koenig
				  ark at europa.att.com



More information about the Comp.lang.c mailing list