Home > Blockchain >  Address of an array different with the address of the first element?
Address of an array different with the address of the first element?

Time:06-06

As I know address of array a is the address of first element of this array.

void func(int a[])
{
    cout << "address in func: " << &a << endl;;
    cout << "GT: " << &a[0] << endl;
}
int main ()
{
    int a[] = {0,1,2,3};
    cout << "address in main: " << &a << endl;
    cout << "address in main a[0]: " << &a[0] << endl;

func(a);
}

Output:

address in main: 0x7ffef67d6790

address in main a0: 0x7ffef67d6790

address in func: 0x7ffef67d6778

GT: 0x7ffef67d6790

Why address of array a in func() difference with address of a[0]?

CodePudding user response:

Why address of array a in func() difference with address of a[0]?

Because you're calling the function func() passing a by value. This means the a inside the function func() is actually a copy of the original decayed pointer that you're passing to func() from main(). And since they're different variables, they have different addresses. Thus by writing cout << &a; you're printing the address of this separate local variable named a.

If you want to print the original address, you should write inside func():

void func(int a[])
{
//---------------------------------v---------->removed the &
    cout << "address in func: " << a << endl;;
    cout << "GT: " << &a[0] << endl;
}

Demo

address in main: 0x7ffcfb0a4320
address in main a[0]: 0x7ffcfb0a4320
address in func: 0x7ffcfb0a4320
GT: 0x7ffcfb0a4320

CodePudding user response:

As it has been explained in the comments, you're not passing the "same" variable to your function. When you're calling your function, it makes a local copy within it of your array of int.

In order not to waste memory, and let's say you upgrade your program and now, you're not passing to your function an array of int but a std::vector which is quite big, we have in C arguments passed by references (myType & myVar).

This is the same than passing an argument by pointers in C. Passing something by reference actually creates an ALIAS to the variable passed. So you'd now have 2 ways to act on the variable : the variable itself in your main program, and the alias in your function.

Obviously, if you do not want to modify it in the function, you can pass it by const reference (const myType & myVar) which is the same than in C with const *.

CodePudding user response:

It is a fallacy inherited from C that

void func(int a[])

would pass an array to the function.

While int a[] looks like an array you can't actually pass an array to a function. An array always decays to a pointer and the pointer is actually what you pass to the function. So the above is equivalent to writing

void func(int *a)

and maybe now you can see why &a, the address of the local pointer, and &a[0] the address of the first element of the array are different.

  •  Tags:  
  • c
  • Related