为什么在打印指向字符类型的指针时 C++ 会显示字符? [英] Why does C++ show characters when we print the pointer to a character type?
问题描述
考虑以下代码:
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?
推荐答案
将指针传递给字符被解释为以 NULL 结尾的 C 字符串,因为非成员 std::ostream<<<(ostream&) 重载具有重载对于 NULL 终止的 C 字符串(const char *).
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 );
在你的情况下,它只是一个字符,随后的内存位置是垃圾,ostream 读取内存,直到它在内存流中遇到 NULL.
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.
如果您确实需要传递字符指针并显示地址,您可以利用格式化插入器 operator<<
成员重载 void *
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 );
要访问它,您需要一个从 char *
到 const void *
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;
这篇关于为什么在打印指向字符类型的指针时 C++ 会显示字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!