I have the following code:
#include <iostream>
using namespace std;
int main()
{
int g[] = {9,8};
int (*j)[2] = &g;
cout << "*(j):" << *(j) << endl;
cout << "j:" << j << endl;
cout << "&j:" << &j << endl;
cout << "&(*j)" << &(*j) << endl;
cout << "*(*j):" << *(*j) << endl;
return 0;
}
which ouputs:
*(j):0x7fff5ab37c7c
j:0x7fff5ab37c7c
&j:0x7fff5ab37c70
&(*j)0x7fff5ab37c7c
*(*j):9
I think that j is a pointer to an array of two integer.
And &g is the address of the whole array.
Then j store the address of the whole array.
And so I use the *(j), it will dereference the first element in the array.
But the result said that *(j) store the array address the same value as j.
I cannot figure out how this happened.
"I think that
j
is a pointer to an array"Yes, it is. And that's also the reason why
*j
output the same address as outputtingg
would do. In this case an array decays into the pointer and that's why even outputtingj
yields the same result.The fact that the same address is outputted might make you think that
j
and*j
are the same pointers, however they are not. Their type is different (a fact that actually matters):so using
*j
becomes equivalent to usingg
directly, just like*(*j)
becomes equivalent to*g
.And
&(*j)
is nothing butj
, which is initialized withan address of an array(an address taken from decayedg
, i.e. an address of the first element of this array).So why
j
and*j
outputs the same address and*(*j)
outputs the value of first element?Because of the type of
j
beingint (*)[2]
. A simple example:outputs
9
.That is correct.
This is not.
*j
gives you the array itself. When you insert it tocout
, it decays to a pointer again (this time to a pointer to its first element, typeint*
) and its value is printed.It's in effect the same as if you wrote
cout << g
.