+ 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

7th Jun 2018, 11:32 PM
Gaël Des Iris
Gaël Des Iris - avatar
6 ответов
+ 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.
8th Jun 2018, 1:31 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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);
8th Jun 2018, 1:40 AM
John Wells
John Wells - avatar
+ 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;
8th Jun 2018, 2:23 PM
John Wells
John Wells - avatar
+ 1
Really suprising that you have to cast to get the address of char .
8th Jun 2018, 8:44 AM
Rabilu Ibrahim Muhammad
Rabilu Ibrahim Muhammad - avatar
+ 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 !
9th Jun 2018, 1:42 AM
Gaël Des Iris
Gaël Des Iris - avatar
0
Donna it'll print the address of letr, not the address of letter.
8th Jun 2018, 2:43 AM
Dilip Srinivas
Dilip Srinivas - avatar