问题
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?
回答1:
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;
回答2:
Say you have:
char s[] = "abcd";
char* cp = a;
cout << cp << endl;
The expectation is that you want to see:
abcd
in the output.
std::ostream
has an overload that works with char const*
that takes care of printing abcd
in the above code instead of just the pointer value of cp
.
When you call
cout<<"Value of &char_a is (p_a) :"<< p_a<<endl;
the program expects p_a
to be a null terminated strings. Since it is not, you are seeing garbage.
回答3:
The operator << for std::ostream
is overloaded for char *
(to handle it as a string). If you want to print the address, cast it to (void *)
.
来源:https://stackoverflow.com/questions/25801237/why-does-c-show-characters-when-we-print-the-pointer-to-a-character-type