Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between memory map of static 2-d array and dynamic 2-d array?

from my understanding when we create array using pointers like this

    int **ptr = new int*[2];

    for(int i=0;i<2;i++)
     {
       ptr[i] = new int[3];
     }

it would look something like this enter image description here

but when we create a static array like this

 int arr[2][3]={1,2,3,4,5,6);

and now if we run the following code

cout<<"Address of arr = "<<&arr;
cout<<"arr is pointing to = "<<*arr;

it shows the same address, which means arr is pointer which is pointing to itself, which seems very confusing because if array is double pointer then how can it point to itself.

clearly compiler is doing some odd things behind the scene. could you please explain how this works.

like image 327
mightyWOZ Avatar asked Feb 27 '26 03:02

mightyWOZ


1 Answers

it shows the same address, which means arr is pointer which is pointing to itself

No, it doesn't mean that. What it means is that the address of arr is the same as the address of arr[0][0]. This makes perfect sense, because arr[0][0] is part of arr, and is in fact at the very beginning of it. Similarly, you will find my left arm in the exact same location as you will find me.

The difference between &arr and *arr is the type. &arr is of type int (*)[2][3] (pointer to an array of 2 arrays of 3 ints), whereas *arr is of type int[3] (array of 3 ints). This difference is not expressed by your cout statements, simply because operator<< is not defined to express it.

like image 142
Benjamin Lindley Avatar answered Feb 28 '26 18:02

Benjamin Lindley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!