0
Why a char pointer did not work?
I tried the following snippet: char ghost='f'; char *ptrG; ptrG = &ghost; cout << ptrG; I wanted to see the address, but the output was 'f'. What did I do wrong?
6 Respuestas
+ 2
The reason is the << is overloaded operator and if you give him the adress of the string begining, it prints out the string. If you really want to see the adress, you should cast the pointer to void.
cout << static_cast <const void *>(ptrG);
static and const are there to ensure you won't mess up the content, but considering it's just printing you may use:
cout << (void *) ptrG;
Or if you prefer use printf since it doesn't decide how to print, so you can tell it what to do.
It also works wrong in code blocks, so no worries.
0
use
cout << *ptrG ;
0
Nothing wrong, your code works.
0
Well, it works wrong in the Playground. I saved the snippet in public file. Every time I run it, I get the same value f instead of a memory address.
0
Maybe Playground works wrong...
If you try to delete the two other parts with int and double, then the char address result "f +("
I have tried your code in another compiler (cppdroid) and the result is a 11 character string. And if you try to print &ghost, the result is the same...
0
Thank you Milica for your thorough answer. It helped a lot.
Thank you all guys for comments