Recently I've been learning about C++ pointers and I'm confused when it comes to char.
char *c = "sampletext";
cout<< *c <<endl;
cout<< c <<endl;
cout<< &c <<endl;
To be more precise: why does cout<< c <<endl;
print whole C-string instead of address (as it takes place in int pointers for example), and why does cout<< *c <<endl;
print first letter instead of whole C-string. Thank you in advance
This happens because the compiler checks the type of the argument and calls the overloaded version of the operator that receives that type.
In the C language, strings are implemented as char
arrays terminated with the '\0'
(nul) character, and arrays are referred to using pointers. So, when the argument received is c
, the overloaded operator that receives a char*
prints the content of the array up to the nul terminator.
When the argument received is *c
, this dereferences the pointer to access its data, and since this is a pointer to char
, the overloaded operator that receives a char
prints it as a single char
.
To print the address of the string array, you can cast the char*
pointer to void*
, like follows:
std::cout << (void*) c << std::endl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.