Home >Backend Development >C++ >How to Print a Pointer Address with C \'s cout?

How to Print a Pointer Address with C \'s cout?

DDD
DDDOriginal
2024-11-04 00:22:30350browse

How to Print a Pointer Address with C  's cout?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn