Re: array -- foo, &foo and &foo[0]
- From: "Doug Harrison [MVP]" <dsh@xxxxxxxx>
- Date: Tue, 14 Aug 2007 00:20:13 -0500
On Mon, 13 Aug 2007 21:48:01 -0700, George
<George@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
Hello everyone,
I think if we define foo as char array, for example,
char foo [32];
then foo, &foo and &foo[0] should be the same, right?
For example, the following 3 statements are the same,
strcpy (foo, goo);
strcpy (&foo, goo);
strcpy (&foo[0], goo);
Any comments?
The second one won't compile, because the first argument has the wrong
type. I consider the third one bad style, while the first one uses the
preferred syntax.
I am very interested in how C treats foo and &foo and make them the same?
They have the same value, but the types are different. When you say:
foo
The array "foo" undergoes the array-to-pointer conversion in most contexts
(the main exception being sizeof(foo)), which produces a pointer to the
first element of the array. This pointer has type char*, or "pointer to
char". However, when you say:
&foo
You are taking the address of the array, and the resulting pointer has the
type:
char (*)[32]
This is a "pointer to an array of 32 char". To see the difference between
the two, consider the effect of incrementing the pointers. Note also that
if you had:
char x[10][32];
and you said:
x
The array-to-pointer conversion would produce a pointer to the first
element of the array x, which is an array of 32 char, so the type of the
pointer would again be char(*)[32].
Taking the address of an array is rarely useful. As for &foo[0], this is
taking the address of the first element of foo, so it produces the same
value as saying foo, and it has the same type. You need to use the &foo[0]
syntax when dealing with classes such as std::vector, which do not undergo
the array-to-pointer conversion, and I suppose you might also need to use
it when calling certain function templates. Another use would be to
emphasize that you are working on a single element, rather than the whole
array, which is more or less implied when you say foo.
--
Doug Harrison
Visual C++ MVP
.
- Follow-Ups:
- Re: array -- foo, &foo and &foo[0]
- From: George
- Re: array -- foo, &foo and &foo[0]
- Prev by Date: Re: solution name change
- Next by Date: Re: array -- foo, &foo and &foo[0]
- Previous by thread: InterlockedExchange64
- Next by thread: Re: array -- foo, &foo and &foo[0]
- Index(es):
Relevant Pages
|