为什么指向 char 的指针与其他数据类型的指针相比行为不同
why pointer to char behaves differently as compared to pointersof other data types
我对以下陈述有疑问;
int intvalue = 3;
int *pointInt = &intvalue;
char* p = "string";
cout << pointInt << std::endl; // this will give memory location of intvalue which is ok.
cout << p<< std::endl; // why this will give string value rather than memory location of where string is stored?
因为存在 std::ostream& operator<<(std::ostream&, const char*)
的重载,它假定char*
是以 null 结尾的字符串的第一个元素并打印出整个字符串。
通过尝试流式传输不是以 null 结尾的字符串的第一个元素的char*
,您可以获得很多乐趣:
#include <iostream>
int main()
{
char c = 'x';
std::cout << &c << std::endl;
}
char*
和const char*
最常用于指向以 C 样式的 null 结尾的字符串。标准 I/O 库在传递要插入或提取到的类型之一时会考虑到这一点。这些函数只是根据想要打印出 C 样式字符串的常见程度来设计为具有这种特殊情况。
若要获取指针值,可以尝试强制转换为其他指针类型:
std::cout << static_cast<void*>(p) << std::endl;
关键字运算符重载 - 只是iostream实例的另一种方法,std::cout
负责字符并以不同的方式处理。确切的实现也可以产生"Hello World">
cout << (void *) p << std::endl;
我希望这是因为<<
运算符对char*
参数有一个特定的覆盖,以输出字符串。
这是
operator<<()
cout 对象的类型作为第一个参数并将类型char*
或const char*
作为第二个参数的重载。
有很多这样的重载,你也可以写一些。
这种特殊重载的原因是"打印"C 样式字符串(以 null 结尾的字符数组(
相关文章:
- 结构和双指针隐藏在其他结构中,多层混淆
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 包含指向其他结构的指针向量的结构
- 我可以使用 decltype() 或其他东西通过指针获取真实类型吗?
- 在指针中对其他信息进行编码
- char* 除了作为C++中的指针之外,还有其他功能吗?
- C++ 指向其他类函数的指针函数
- 当动态库中的指针仍被其他库使用时,如何删除该指针
- 指向用随机指针归档的其他类对象的指针的c++向量
- Sizeof返回的是指针大小,而不是数组大小.有其他方法可以找到尺寸吗
- 如何知道指针是否已在其他地方释放
- 为什么C++让你把"->"符号放在指针上,把"."符号放在其他所有东西上?
- fprintf 不打印到文件,当文件指针在其他地方声明时
- QPointer::clear() 是删除其引用的指针,还是"Clears this QPointer object."其他含义?
- 与其他语言相比的 Ruby 和指针
- 如何在没有作弊引擎的情况下从其他应用程序获取指针地址?
- 为什么可以将所有类型转换为其他指针类型?
- 将指针类方法作为参数传递给其他类方法C
- 将指针与其他数据相关联
- 如何复制包含指向其他几个成员之一的指针的对象?