I have a "v" array that I want to pass to a function. Are "v" and "&v" equivalent or is there any difference between them?
For example:
char v[4]
scanf("%s", v);
scanf("%s", &v);
I have a "v" array that I want to pass to a function. Are "v" and "&v" equivalent or is there any difference between them?
For example:
char v[4]
scanf("%s", v);
scanf("%s", &v);
v
is address of v[0]
and &v
is address of whole array. Fortunately both will have same value. But any arithmetic on these pointers will access differently. For example
(v+1)
and (&v + 1)
are not same.
scanf
expects the argument corresponding to %s
to have type char *
; the expression &v
will have type char (*)[4]
. Even though the values will be the same, the types will be different, and type matters.
For this case, you want to call it as
scanf("%s", v);
You can always ask to the compiler itself...:
#include <stdio.h>
int main()
{
char v[4];
printf (" v &v &v[0]\n");
printf ("%p %p %p\n", v, &v, &v[0]);
printf ("%p %p %p\n", v+1, &v+1, &v[0]+1);
return 0;
}
Using MinGW2.95 , this prints the following:
v &v &v[0]
0240FF24 0240FF24 0240FF24
0240FF25 0240FF28 0240FF25
As you see, the three expressions yield the same value for the base array address, so they can be used with scanf()
(although I agree that the correct expression for scanf()
is the first one). If you want to perform some arithmetic pointer on these, they have not the same type.
v
, &v
, &v[0]
differ by type but by value they're the same.
v
is of type char[4]
; array of 4 char
s&v
is of type char (*) [4]
; pointer to an array of 4 char
s&v[0]
is of type char*
; pointer to a char