Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ show characters when we print the pointer to a character type? [duplicate]

Tags:

c++

pointers

Consider the following code:

char char_a = 'A';
int int_b = 34;

char* p_a = &char_a;
int* p_b = &int_b;

cout<<"Value of int_b is (*p_b) :"<< *p_b<<endl;
cout<<"Value of &int_b is (p_b) :"<< p_b<<endl;

cout<<"Value of char_a is (*p_a) :"<< *p_a<<endl;
cout<<"Value of &char_a is (p_a) :"<< p_a<<endl;

When I run it, output is:

enter image description here

So why doesn't it show the address in the case of char pointer as it does for the integer's pointer?

like image 668
Failed Scientist Avatar asked Sep 12 '14 05:09

Failed Scientist


1 Answers

Passing a Pointer to a character is interpreted as a NULL terminated C string as the non member std::ostream<<(ostream&) overload has an overload for NULL terminated C string (const char *).

template< class CharT, class Traits >
basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os, 
                                         const char* s );

As in your case, it's just a character and the subsequent memory locations are garbage, the ostream reads the memory until it hits a NULL in the memory stream.

This is definitely an undefined behavior as you would be accessing memory beyond those that had been allocated to your process.

If you actually need to pass the character pointer and display the address, you can leverage the formatted inserter operator<< member overload for void *

basic_ostream& operator<<( const void* value ); 

To access this, you need an explicit pointer cast from char * to const void *

std::cout << "Value of &char_a is (p_a) :" << static_cast<const void *>(p_a) << std::endl;
like image 72
Abhijit Avatar answered Oct 09 '22 22:10

Abhijit