Address of array

Gregory Smith greg at utcsri.UUCP
Sun Mar 9 04:45:12 AEST 1986


In article <750 at abic.UUCP> jst at abic.UUCP (Shack Toms) writes:
>I have noticed that different compilers treat the & operator differently
>when it is applied to arrays.  In particular, the UNIX compiler I have
>been using warns against it.  K&R explicitly deny its legality.
>However, the operation seems to me to be perfectly
>reasonable when the desired result is a pointer to the array rather
>than a pointer to the first element of the array.  For example,
>[examples]

The problem is that & can only be used on lvalues, and an array can
never be an lvalue, even though its address is known. This is done
because of the automatic 'array-to-pointer' conversion in C. If an
array was an lvalue, what could you assign to it? another array! but
this second array reference would be automatically converted to a
pointer so that wouldn't work.

I agree that it is really a design flaw in the language, to make
it illegal to form a pointer to an array. & should work on any
'object' ( an object of known type residing in memory at a computable
address ) where an object is an lvalue or an array.

The problem could also be solved by allowing arrays to be lvalues.
The array-to-pointer conversion would have to be suppressed depending
on the operation being done on the array. If the array was the object of a
&, or if it was on one side of an '=', with an identical type array on
the other side, the array-to-pointer conversion would not be done. This
would allow array assignments within the current syntax of c. It would not
allow arrays to be passed as parameters, though, since parameter types of
called functions are not known to the compiler. The semantics as described
above for the '=' operator would probably very messy to implement, too.
For these reasons I think that & should be allowed but not =.

Incidentally, the language as described in K&R requires the array-to-pointer
type conversion to be supressed depending on the context of the array, but
only in one case, the object of a sizeof:

	char line[80];
	sizeof( line )	== 80	/* line not converted to (char*) */
	sizeof( line+1 ) == 4	/* or 2 or whatever sizeof(char*) is */

This exception is noted in K&R 7.2 : "When [ sizeof is ] applied to an array,
the size is the total number of bytes in the array". I.e. they are noting that
it is a special case of array treatment. (7.2 of the language reference,
Appendix A ).

Adding another, similar special treatment would allow pointers to arrays.
'&line' in the above example would be of type ( char (*)[80]).

-- 
"So this is it. We're going to die."	- Arthur Dent
----------------------------------------------------------------------
Greg Smith     University of Toronto       ..!decvax!utzoo!utcsri!greg



More information about the Comp.lang.c mailing list