请考虑以下代码:
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;
Run Code Online (Sandbox Code Playgroud)
当我运行它时,输出是:

那么为什么不在char指针的情况下显示地址,就像它对整数的指针一样?
Abh*_*jit 14
将指针传递给字符被解释为NULL终止的C字符串,因为非成员std :: ostream <<(ostream&)重载具有NULL终止的C字符串(const char*)的重载.
template< class CharT, class Traits >
basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os,
const char* s );
Run Code Online (Sandbox Code Playgroud)
在你的情况下,它只是一个字符,后续的内存位置是垃圾,ostream读取内存,直到它在内存流中遇到NULL.
这绝对是一种未定义的行为,因为除了那些已分配给您的进程的内存之外,您将访问内存.
如果您确实需要传递字符指针并显示地址,则可以利用格式化的插入器operator<<成员重载来实现void*
basic_ostream& operator<<( const void* value );
Run Code Online (Sandbox Code Playgroud)
要访问它,您需要从中char *转换显式指针const void *
std::cout << "Value of &char_a is (p_a) :" << static_cast<const void *>(p_a) << std::endl;
Run Code Online (Sandbox Code Playgroud)