DEV Community

hwangs12
hwangs12

Posted on

Pointer & Reference & Deference in C++

Say you have a variable 'a' of type integer.
int a = 4;

Then, you can find the address of 'a' using pointer.
int *b = &a;

Well, not exactly because '&a' will give you the address as well. Try,
cout << &a; // will output address of the variable a

But, back to the pointer, it gives you the ability to 'save' the address of memory. Hence, it will show memory address of 'a' as well. Try,
cout << b

What would happen if I try printing out *b? It will give you the value of 'a'. Weird, isn't it? This behavior is called dereferencing, meaning you get the actual value of whatever is saved in that memory.

Does b have memory address as well? Yes, you can access it with '&b'

So, in summary

int a = 4; // note it has memory allocated to this integer
int *b = &a; // you can save the memory address to a variable 'a'
cout << b; // it will give you memory address of 'a'. Notice how it is not saved in '*b' but 'b' itself. 
cout << &a; // this will give you memory address of 'a'
cout << *b; // this will give you the value of 'a'. Dereferenced!
Enter fullscreen mode Exit fullscreen mode

Question remains: what would &*b produce? what will *&a produce?

Answer:
&*b -> it is address of pointer to 'a', hence same as &a, memory address where 'a' is saved.
*&a -> * dereferences memory address aka finds out the value in the address hence value of 'a'

Top comments (0)