Pointer to array needs double dereferencing

Feb 23, 2015 at 7:35pm
Hi,

I've defined a pointer to array of 4 ints.
Now, dereferencing that pointer still causes it to display the address it points to instead of the value that it points at.

Dereferencing it second time causes the value to be displayed, but I have no idea why is that so. Here's the code :

1
2
3
4
5
int arr[] = {1,4,6,8};
int (*pint3)[4] = &arr;
std::cout << (pint3) << "\n";  //prints the address of 0 element of arr 
std::cout << (*pint3) << "\n"; //still prints the address of 0 element of arr - why ?
std::cout << (**pint3) << "\n"; //now prints the value of the 0 element of arr - why is the double dereference needed ? 


Thanks in advance!
Last edited on Feb 23, 2015 at 7:36pm
Feb 23, 2015 at 7:51pm
Feb 23, 2015 at 8:01pm
Dereferencing it second time causes the value to be displayed, but I have no idea why is that so.

Because *pint3 is a pointer to an array of 4 ints.

Why didn't you just declare it as a pointer to an int?

int *pint3 = &arr;

Feb 24, 2015 at 5:19pm
Thanks, Tarik. I get it now.

Because *pint3 is a pointer to an array of 4 ints.


Not to be rude, but that explanation would be hardly helpful. I'm just playing around with pointers for learning purposes.
Feb 24, 2015 at 5:36pm
Not a problem mate. It can be a very difficult process to how pointers work exactly. Goodluck to you!
Topic archived. No new replies allowed.