Hi guys,
As far as I know, for any type T, and positive integer N, if I have an
array declared as:
T array[N];
then,
&array[0] and array are the same element. Is there any reason why a
programmer should use the first and not the second way to refer to the
base adress of the first element of the array?
The two forms are equivalent in almost all contexts
(the two exceptions: `sizeof &array[0]' does not mean the
same thing as `sizeof array', and `& array' has a meaning
while `& &array[0]' does not). In the contexts where the
two forms mean the same thing to the compiler, the only
reason to choose one or the other is to help the human
reader of the code. I'd suggest the following as loose
guidelines for the choice:
- If you're "talking about" the array as a whole,
write `array'. For example, if you're passing the
array to a function that makes use of its "array-ness"
(the way qsort() or strlen() do), write `array'.
- If you're "talking about" one object that just happens
to reside in an array, `&array[0]' may help emphasize
the point. For example, you might write something
like `bsearch(&array[0], values, ...)' to suggest that
bsearch() will look at all of `values' but only at the
single key `array[0]'.
- More generally, I'd suggest writing `array + j' when
talking about the sub-array from element `j' onward,
or `&array[j]' when talking about just the one element.
These are, of course, just stylistic matters -- and matters
of style have a tendency to become matters of religion, so
it's likely others will disagree with the way I like to do
things. I must also admit that I'm not 100% consistent in
following the practices I recommend ... Take it or leave it.