Address of array

Kenneth Almquist ka at hropus.UUCP
Tue Mar 25 04:46:37 AEST 1986


> I don't really see what the problem is that people are moaning
> about.  If you want a pointer to the array, the array name itself
> coerces to a pointer containing the memory location at the beginning
> of the array.  There is no such thing as a pointer to the whole
> array:  that is a Pasqualische or Fortranian notion.  Pointers, in
> C, only point to atomic or aggregate (structure/union) objects.

Actually, there is such a thing as a pointer to an array in C; otherwise
multi-dimensional arrays would not work.  For example:

	int a[5][10];

This declares "a" to be an array of arrays.  A reference to "a" is normally
converted into a pointer to the first element of "a", and the first element
of "a" happens to be an array of 10 integers.  Now let's try to do something
with a:
	int (*p)[10];

	for (p = a ; p < a + 5 ; p++) {do something;}

Some people would prefer to replace "a + 5" with "&a[5]" on stylistic
grounds, but the latter is currently illegal because the address of arrays
cannot be taken.  If we want to have "p" point to a simple array of 10
elements, things get rather awkward:

	int b[10];

	p = ((*)[10])b;

This works, but it is not as readable as "p = &b".  If we don't want to
duplicate the constant "10", the above assignment must be changed to:

	p = ((*)[sizeof b / sizeof b[0]])b;

We cannot write "p = b" because references to "b" are converted to "pointer
to int" while "p" is of type "pointer to array[10] of int".

To repeat the basic proposal:  the conversion of an array expression to
a pointer to the first element of the array is inhibited when the "sizeof"
operator is applied to an array expression; this conversion could also
be inhibited when the "&" operator is applied to an array expression.  This
would not be a major improvement to the language, but would make certain
types of code slightly cleaner.  It is a simple extension to C which should
not break any existing programs.  In fact, the original C compiler written
by Dennis Ritchie allowed "&" to be applied to arrays.
				Kenneth Almquist
				ihnp4!houxm!hropus!ka	(official name)
				ihnp4!opus!ka		(shorter path)



More information about the Comp.lang.c mailing list