char c = 'a';
char* p = &c;
cout << p << endl;
cout << *p << endl;
This is a code written in C++ language.
Why in the first cout statement the program tries to print until it finds a null character and in the second statement it just prints a single character?
In C++, pointers to char
are often considered a "C string" by convention -- which is a null-terminated string of char
s. This is an expected convention in much of the C++ standard library -- and this holds true in std::ostream
as well.
In particular, in your two calls:
p
will call std::ostream
's operator<<(const char*)
overload -- which prints it as a null-terminated character string, andchar
*p
will call std::ostream
's operator<<(char)
overload for characters, which prints the singular character Note: If you want to print the address of the pointer itself, you will want to call the operator<<(const void*)
overload -- which requires an explicit cast to void*
:
std::cout << static_cast<void*>(p) << std::endl;
This operator is not discovered automatically since the language sees that operator<<(const char*)
does not require any type conversions to take place for p
.
It's specific thing of C and C++. Pointer of char means string with zero symbol at end.
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.