How to Output a Pointer Address with C 's cout
When attempting to print a character pointer using cout, the stream decides to treat it as a string rather than an address. This behavior arises because of overload resolution, where cout selects an operator that matches the argument's type.
In this case, cout chooses the operator defined for printing C-style strings:
<code class="cpp">ostream& operator<<(ostream& o, const char *c);
However, you need to select the overload for printing pointers:
<code class="cpp">ostream& operator<<(ostream& o, const void *p);
To explicitly cast the char pointer to a generic pointer, use the following syntax:
<code class="cpp">cout << static_cast<void *>(cptr) << endl;</code>
This cast informs cout that you intend to output the pointer's address rather than the string it points to.
The above is the detailed content of How to Print a Pointer Address with C \'s cout?. For more information, please follow other related articles on the PHP Chinese website!