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:
So why doesn't it show the address in the case of char pointer as it does for the integer's pointer?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With