简体   繁体   中英

C++ pointer address explanation

I am new to C++ and I have a piece of code like this:

int firstvalue=10;
int * mypointer;
mypointer = &firstvalue;
cout << "pointer is " << *mypointer << '\n';
cout << "pointer is " << mypointer << '\n';
cout << "pointer is " << &mypointer << '\n';

The result is:

pointer is 10
pointer is 0x7ffff8073cb4
pointer is 0x7ffff8073cb8

Can anyone explain to me why the result of "mypointer" and "&mypointer" are different?

Thanks a lot.

  • mypointer is the value of the variable mypointer . And that value is, due to your assignment, the address of firstvalue .
  • &mypointer is the address of the variable mypointer . That is, the address of mypointer .

So, mypointer is the address of firstvalue , and &mypointer is the address of mypointer . Since firstvalue and mypointer are distinct variables, they have different addresses.

See inscribed comments

int firstvalue=10; // first variable, stored at say location 2000, so &firstvalue is 2000
int * mypointer; // second variable, stored at say location 2004, so &mypointer is 2004
mypointer = &firstvalue; // mypointer had garbage, now has 2000
cout << "pointer is " << *mypointer << '\n'; // contents of mypointer i.e. firstvalue (10)
cout << "pointer is " << mypointer << '\n'; // value of mypointer i.e. 2000
cout << "pointer is " << &mypointer << '\n'; // address of mypointer i.e. 2004

got it?

In the example, the & operator means "the address of". Therefore "mypointer" is the address of the value 10, but "&mypointer" is an address of an address whose value is 10.

firstvalue is a variable which can hold an int type value. This variable has its own address 0x7ffff8073cb4 .

myvariable is a (pointer) variable that can hold the an int * type value, ie address of a variable that can hold int type value. This variable has its own address 0x7ffff8073cb8 .

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM