Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Address of an array different with the address of the first element?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

address in main a0: 0x7ffef67d6790

address in func: 0x7ffef67d6778

GT: 0x7ffef67d6790

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading