0

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);
Marco Fazio
  • 61
  • 2
  • 6

5 Answers5

2

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.

Dayal rai
  • 6,548
  • 22
  • 29
1

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);
John Bode
  • 119,563
  • 19
  • 122
  • 198
1

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.

mcleod_ideafix
  • 11,128
  • 2
  • 24
  • 32
0

Yes If you want to know base address of array then you can just write v i.e. It will give

address of first element in array.and &v will give address of complete array.

v[0] is same as (v+0), v[1] is same as (v+1) and so on.

hope you get it.

Chinna
  • 3,930
  • 4
  • 25
  • 55
Coder
  • 116
  • 1
  • 15
0

v, &v, &v[0] differ by type but by value they're the same.

  • v is of type char[4]; array of 4 chars
  • &v is of type char (*) [4]; pointer to an array of 4 chars
  • &v[0] is of type char*; pointer to a char
legends2k
  • 31,634
  • 25
  • 118
  • 222