-1

I am a newbie to pointers and am facing some problems while trying to understand them.

Now I looked up this problem over here. I was not 100% satisfied with the solution. So I did some checking on my own to see what happens.

I wanted a pointer to a two-dimensional array so I tried:

int arr[2][3] = {{12,23,4},{323,43,3}};
int (*ptr)[3] = arr; // A pointer to the first element of array.
                     // The first element of array is an array of three ints.

I ran the following code:

std::cout<<ptr<<std::endl;
std::cout<<*ptr<<std::endl;

Now the results I got were a bit confusing for me:

0x61fdc0
0x61fdc0

Both times the same output is shown. How can the address of the pointer and value after the referencing be the same? Is this behavior similar to double pointers? An explanation like this will be very helpful.

VIAGC
  • 639
  • 6
  • 14

1 Answers1

1

Arrays can decay to pointers. Actually you used that fact when you wrote:

int (*ptr)[3] = arr;

ptr is "a pointer to the first element of array". The 2D array arr did decay to a pointer to its first element when you used it to initialize ptr.

When you dereference ptr you get the first element (of arr), a one-dimensional array, and when you print it via

std::cout << *ptr << std::endl;

you get its address printed, because the array decays to a pointer to its first element.

As the answer you link explains, the address of an array and the address of its first element are identical:

The following are equivalent ways to point to the first of the two items.

int (*p)[3] = a; // as before
int (*p)[3] = &(a[0]);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185