When dealing with char pointers, the choice between outputting the address or the string content can be confusing. In the case of printf(), the decision is clear-cut based on the conversion specifier. However, when it comes to cout, the selection process is less obvious.
In C , cout is an instance of the ostream class, which offers multiple overloaded versions of the operator<<. When printing a char pointer, the compiler must determine which overload to use. By default, cout will prioritize the overload meant for C-style strings, which prints the string content.
To override this behavior and print the address instead, a cast is necessary. The desired overload takes a void pointer as input. Therefore, you can use the following code:
cout << static_cast(cptr) << endl;
This cast explicitly converts the char pointer to a void pointer, forcing cout to use the appropriate overload. As a result, the address of ch will be printed.
The above is the detailed content of How to Print the Address of a char Pointer using cout in C ?. For more information, please follow other related articles on the PHP Chinese website!