"Ancient_Hacker" <gr**@comcast.netwrites:
[...]
The general rule is, the name of an array *is* the address of the
array. This funny shortcut exists because there are NO operations in C
that can take place with the VALUE of a whole array, so an array name
cannot mean "get me the value", so it defaults to "gimme the address".
Only if by "general" you mean "incomplete".
The general rule is this (C99 6.3.2.1p3):
Except when it is the operand of the sizeof operator or the unary
& operator, or is a string literal used to initialize an array, an
expression that has type "array of _type_" is converted to an
expression with type "pointer to _type_" that points to the
initial element of the array object and is not an lvalue. If the
array object has register storage class, the behavior is
undefined.
So you never have to put an ampersand in front of an array name. Many
compilers put out an informative warning if you do so.
&array is a perfectly legitimate expression; it yields the address of
the array, which is distict from the address of its first element.
They have the "same value" in some sense, but they're of different
types.
For example, given "int array[10];", the expression "array + 1" is of
type int* and yields the address of the second element of array, and
the expression "&array + 1" is of type int(*)[10] (pointer to array of
10 ints), and yields a pointer just past the end of the object.
Most arrays are accessed via pointers to their elements, so taking the
address of a full array is relatively rare -- but it is meaningful,
and quite distinct from taking the address of an array element.
This doesnt apply if the array is subscripted! For example, array[1]
is manipulable by C's code generator, so array[1] means the VALUE of
that element. So if you need to pass the address of that element, you
do need an ampersand.
On the contrary, the actual rule does apply to subscript operations.
The subscript operator, x[y], is by definition equivalent to *(x + y),
where one operand is a pointer and the other is an integer. In the
expression "array[5]", the expression "array" is implicitly converted
to a pointer. This is just the normal conversion that usually happens
to array expressions; it has nothing to do with the indexing
operation.
Arrays are not pointers. Pointers are not arrays. It's important to
keep this in mind, in spite of the language's best efforts to make you
think otherwise.
See section 6 of the comp.lang.c FAQ, <http://www.c-faq.com/>, "Arrays
and pointers".
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.