Address of array
Robert Hamilton
rh at cs.paisley.ac.uk
Wed Mar 19 22:29:32 AEST 1986
>In article <211 at dg_rtp.UUCP> throopw at dg_rtp.UUCP (Wayne Throop) 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.
>>
>>I agree that C's treatment of array/function/struct addresses is
>>inconsistant, confusing, and limiting. In essence a small notational
>>convenience was traded for a large consistancy headache. I think the
>>tradeoff was wrong, but I'm not sure that your proposal would clarify
>>things.
>
>I believe that to support reasonable portable code C *must* allow the address
>operator on an array, even if it is not required. Consider:
>
>prog.c:
> #include "globals.h" /* project global symbols and types */
>
> foo() {
> LOCAL m,n;
>
> process(&m);
> }
>
>globals.h:
> typedef long LOCAL[10];
>
>================
>Since LOCAL is a typedef which is an array, the programmer would not be
>able to write code which would work with a legal typedef for LOCAL
>unless the & operator was allowed for an array. To require special code
>to handle arrays and scalars defeats the intent of information hiding,
>and requires global changes to the source is a typedef is changes, for
>instance, from an array to a structure.
Taking the address of an array just doesnt make sense in C.
You can see the reason if you know why the following bit of
code also won't work:
int a[10];
int *b;
a=b; /* makes no sense */
a+=1; /* ditto */
b=a; /* ok of course */
The decl. a[10] does 2 things:
1. reserves storage for 10 elements
2. lets the compiler know that "a" is an int * to
of the first element reserved.
It does *not* reserve storage for a pointer to the storage.
So "&a" only exists during compilation, in the sense that the
compiler holds the address of the reserved storage somewhere
that "somewhere" has an address at compile time.
The decl. int *b on the other hand does 2 different things.
1. lets the compiler know that "b" is an int * ( for pointer arithmetic)
2. and reserves a storage location for b.
so &b does exist at run time.
What I suppose I'm trying to say is that a is a constant and b is a variable.
Maybe what is wanted is the for the compiler to be "clever"
and assume that if you ask for the address of a constant
you really want the constant ?
--
UUCP: ...!seismo!mcvax!ukc!paisley!rh
DARPA: rh%cs.paisley.ac.uk | Post: Paisley College
JANET: rh at uk.ac.paisley.cs | Department of Computing,
Phone: +44 41 887 1241 Ext. 219 | High St. Paisley.
| Scotland.
| PA1 2BE
More information about the Comp.lang.c
mailing list