Why does C ++ show characters when we print a pointer to a character type?

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, the output is:

enter image description here

So why doesn't it show the address in case of a char pointer, how is this done for an integer pointer?

+6
source share
3 answers

Passing a pointer to a character is interpreted as a C string with a NULL termination, since overloading non member std :: ostream <(ostream &) has an overload for a C string with NULL termination (const char *).

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

As in your case, this is just a symbol, and the subsequent memory cells are garbage, ostream reads the memory until it reaches NULL in the memory stream.

This is definitely undefined behavior, as you will be accessing memory outside of those allocated for your process.

If you really need to pass a pointer to a character and display the address, you can use the formatted operator<< overload of operator<< for void *

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

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

 std::cout << "Value of &char_a is (p_a) :" << static_cast<const void *>(p_a) << std::endl; 
+14
source

Say what you have:

 char s[] = "abcd"; char* cp = a; cout << cp << endl; 

It is expected that you want to see:

 abcd 

at the exit.

std::ostream has an overload that works with char const* , which takes care of printing abcd in the above code instead of the cp pointer value.

When you call

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

the program expects p_a be a zero-terminated string. Since this is not the case, you see garbage.

+3
source

The <operator for std::ostream overloaded for char * (to treat it as a string). If you want to type the address, translate it into (void *) .

+3
source

Source: https://habr.com/ru/post/975172/


All Articles