-5
int x = 2;
int y=8;
int* p = &x; 
*p=y;

cout << p <<endl;

my question is: why do I get the memory adress when I Print p and not the actual value since I already dereferenced it in line 4

Cyreex
  • 1
  • 1
    You have to deference the pointer _every time_ you need the pointed-to value. – paolo Jun 28 '22 at 08:52
  • 2
    Dereferencing `p` doesn't change what `p` is. So dereferencing it in line 4 doesn't negate the need to dereference it in subsequent code (assuming you want to access the value pointed to by `p`, rather than the value of `p` itself). – Peter Jun 28 '22 at 09:37

2 Answers2

3
cout << *p << endl;

is what you need. When you try to output something to stdout, compiler automatically infer its type and call the corresponding function. In your case, p is pointer type, therefore the address is printed, and since *p is int type, you should use *p if you want to print the value.

Jerry Xie
  • 51
  • 3
1

I think you have a misconception about dereferencing pointers.

...since I already dereferenced it in line 4

Dereferencing means to retrieve the value the pointer is pointing to. It doesn't change the pointer itself in any way. p is still a pointer after *p=y;.

All *p=y does, is to change the value p is pointing to, it doesn't change the pointer itself.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30