Why a char pointer did not work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

6th Nov 2016, 4:51 PM
Анна Корнийчук
Анна Корнийчук - avatar
6 Answers
+ 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.
6th Nov 2016, 6:02 PM
Milica Todorovic
Milica Todorovic - avatar
0
use cout << *ptrG ;
6th Nov 2016, 5:08 PM
Paul Kabira
Paul Kabira - avatar
0
Nothing wrong, your code works.
6th Nov 2016, 5:57 PM
marcram
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.
6th Nov 2016, 6:02 PM
Анна Корнийчук
Анна Корнийчук - avatar
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...
6th Nov 2016, 6:10 PM
marcram
0
Thank you Milica for your thorough answer. It helped a lot. Thank you all guys for comments
6th Nov 2016, 6:34 PM
Анна Корнийчук
Анна Корнийчук - avatar