简体   繁体   中英

Pointers and references

I am currently learning c++ and pointers inside of c++. I am curious as to why I get a different memory address when I reference a pointer and why it isn't the same as the reference to the variable. Here is my super simple code:

#include <iostream>
using namespace std;
int main() {
int n = 50;
int *p = &n;
cout << "Number: " << n << endl;
cout << "Number with &: " << &n << endl;
cout << "Pointer: " << p << endl;
cout << "Pointer with *: " << *p << endl;
cout << "Pointer with &: " << &p << endl;
}

Why does &p give me a different address than "&n" and "p"? Thank you

First you declare an int variable n with the value of 50. This value will be stored at an address in memory. When you print n you get the value that the variable n holds.

Then you declare a pointer *p pointing to the variable n. This is a new variable that will hold the address to the variable n, where it is stored in memory. When you print p you will get back that address .

You can also ask for the address to where the value of n is stored by using the & symbol. This is what you get when you print &n, this will be the same as the pointer p.

Using the * symbol before a pointer will dereference it, meaning instead of returning the address that is the pointer, it will return the value that the pointer is pointing to. In your case this is an int with the value 50.

Lastly, the pointer *p that you declared is stored at it's own address in memory. Just as you could get the address to the variable n with the & symbol, you can get the address of p by using &p. This will be different from the address of n since it's not where 50 is stored, it's where the pointer to the value 50 is stored.

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