I have read the pointer to array c++ and have some experiment on it.
#include <iostream>
using namespace std;
int main()
{
int g[] = {9,8};
int (*j)[2] = &g;
int *i = g;
int n = (*j)[0];
int m = *(i + 0);
cout << "n:" << n << endl;
cout <<"m:" << m << endl;
cout << "=============" << endl;
cout << "*(j):" << *(j) << endl;//9's address ???
cout << "j:" << j << endl;//9's address ???
cout << "&j:" << &j << endl;//what it is???
cout << "&(*j)" << &(*j) << endl;//9's address ???
cout << "=============" << endl;
cout << "*(i):" << *(i) << endl;//get the value pointered by i
cout << "i:" << i << endl;//i's value store g's address
cout << "&i:" << &i << endl; //i's address
cout << "&(*i):" << &(*i) << endl;//9's address
cout << "=============" << endl;
cout << "*(g):" << *(g) << endl;//get the value pointered by g
cout << "g:" << g << endl;//g's value store 9's address
cout << "&g:" << &g << endl;//9's address???
cout << "&(*g):" << &(*g) << endl;//9's address
return 0;
}
The result is :
n:9
m:9
=============
*(j):0x7fff56076bbc
j:0x7fff56076bbc
&j:0x7fff56076bb0
&(*j)0x7fff56076bbc
=============
*(i):9
i:0x7fff56076bbc
&i:0x7fff56076ba8
&(*i):0x7fff56076bbc
=============
*(g):9
g:0x7fff56076bbc
&g:0x7fff56076bbc
&(*g):0x7fff56076bbc
[Finished in 0.3s]
What I want to ask is:
1.Why
int (*j)[2] = &g;
int *i = g;
if I change either one &g
to g
, or g
to &g
, it will give a compile error, what is the difference?
(I think that the array name is a pointer, so why cannot I use int (*j)[2] = g
and what is the meaning of &g
, it is a pointer already, why get address again?)
2.
Since the &g
and g
, their address are the same, why cannot be exchanged?
3.
Why the &g
's value is 9
's address? Is it store its own address?
4.
Can you explain the j
variable part?
I cannot understand why j
stores the 9
's address and *(j)
gets the 9
's address, &(*j)
gets the 9
's address too?
I am very confused about it now. What I totally understand is about the i
variable part,
g
variable part is confused about the &g
, and the j
varialbe part is all confused.
The int (*j)[2] = &g;
part is confused too.