Home > Backend Development > C++ > body text

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

DDD
Release: 2024-11-04 00:22:30
Original
212 people have browsed it

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);
Copy after login

However, you need to select the overload for printing pointers:

<code class="cpp">ostream& operator<<(ostream& o, const void *p);
Copy after login

To explicitly cast the char pointer to a generic pointer, use the following syntax:

<code class="cpp">cout << static_cast<void *>(cptr) << endl;</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!