Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cout << with char* argument prints string, not pointer value

Tags:

c++

This:

const char * terry = "hello"; cout<<terry; 

prints hello instead of the memory address of the 'h'. Why is this happening?

like image 296
Mr.Puff Avatar asked Jul 23 '13 14:07

Mr.Puff


People also ask

Is string a pointer in c++?

String is an array of characters. And vowels are characters from the set {a,e,i,o,u}. Pointer is a variable that stores the value of memory location on a variable. To find the number of vowels in a string.

What happens when you use std :: cout on the address or value of a char PTR?

The reason for that is that std::cout will treat a char * as a pointer to (the first character of) a C-style string and print it as such.


1 Answers

The reason for that is that std::cout will treat a char * as a pointer to (the first character of) a C-style string and print it as such. If you want the address instead, you can just cast it to a pointer that isn't treated that way, something like:

cout << (void *) terry; 

(or use the const void * cast if you're worried about casting away constness, something that's not an issue in this particular case).


If you're more of a purist than pragmatist, you can also use the C++ static_cast, along the lines of:

cout << static_cast <const void *> (terry); 

though it's unnecessary in this particular case, the cast to a void * will work fine. The following sample code shows all these options in action:

#include <iostream> int main (void) {     const char *terry = "hello";     std::cout << terry << '\n';     std::cout << (void *) terry << '\n';     std::cout << (const void *) terry << '\n';     std::cout << static_cast<const void *> (terry) << '\n';     return 0; } 

outputting (the address may be different in your environment):

hello 0x8048870 0x8048870 0x8048870 

Note that, when using the static_cast, you should ensure you don't try to cast away the constness with static_cast <void *> (that's what const_cast is for). This is one of the checks done by the newer C++ casts and the old-style cast does not have this limitation.

like image 93
paxdiablo Avatar answered Oct 05 '22 08:10

paxdiablo