+ 2
pointer to char
Hi everybody , Why a pointer to a data type 'char' doesn't give an address ? char letter = 'G'; cout << letter; // outputs G cout << &letter // outputs G (why is it G and a squarre instead of an hexadecimal address?) Thanks
6 Respostas
+ 9
Because the ostream operator << is specially overloaded for char pointers. This is used to display C-style strings.
const char* cstr = "Hello World";
char cstr2[] = "Hello World";
std::cout << cstr;
The pointer points to the first character in the string. Printing the pointer/array using std::cout would cause the program to display all characters until a terminating character '\0' located at the end of the string, is encountered.
+ 8
It is defaulting to a string (e.g. char*x="test";). To get an address, you need to cast it.
cout << static_cast<void*>(&letter);
+ 5
Rabilu Muhammad Ibrahim since a character address is the default for strings, it must be. Otherwise, both of these would output the address.
char str[] = "test";
char *strg = "test";
cout << str << strg;
+ 1
Really suprising that you have to cast to get the address of char .
+ 1
John Wells , Hatsy Rei, thank you very much for you answer.
unfortunatly , i'm beginner with c++ and pointer so i need more progress to understand correctly your answer.
but , i understood that there is a logical reason for this output, i'm happy with that !
0
Donna it'll print the address of letr, not the address of letter.