Home > Enterprise >  Why Do I get the memory adress instead of the real value ? Pointer c
Why Do I get the memory adress instead of the real value ? Pointer c

Time:06-28

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related