【问题标题】:Why does printing a char pointer and an int pointer have a different result? [duplicate]为什么打印 char 指针和 int 指针会产生不同的结果? [复制]
【发布时间】:2020-11-10 09:26:20
【问题描述】:
const char* arr[3];

arr[0] = "Hello";
arr[1] = "C++";
arr[2] = "World";
for (int i = 0; i < 3; i++) {
    cout << arr[i];
}
int* pInt[3];
for (int i = 0; i < 3; i++)
{
    pInt[i] = &i;
    cout << pInt[i] << endl;
}

我将字符地址保存到数组中(arr),输出为HelloC++World。 我第二次将 int 地址保存到数组中(pInt),输出是地址。为什么不一样?

【问题讨论】:

  • 将标题集中在问题上。学习很好,但不如手头的问题重要。
  • 提示:const char* arr[] = { "Hello", "C++", "World" }; 更好的是,了解std::vector。然后你就可以for (auto&amp; s : arr)了,超级简单。
  • 流插入运算符&lt;&lt; 将指向char 的指针视为“C 样式”字符串。这就是cout &lt;&lt; "Hello"; 打印“Hello”而不是数字地址的原因。
  • 请注意,在 C++ 中,在大多数情况下,您宁愿使用 std::string 而不是 char 数组。

标签: c++


【解决方案1】:

为什么不一样?

因为有一个特殊的std::ostream::operator&lt;&lt;(const char *) 重载,它会打印const char * 指向的字节的内容。

没有std::ostream::operator&lt;&lt;(int *),所以编译器选择了一个不同的。编译器选择从int *void * 进行隐式提升,并选择std::ostream::operator&lt;&lt;(const void *) 来打印值。 operator&lt;&lt;(const void *) 以某种实现定义的格式打印指针地址。

如果要打印const char * 指针的地址,请将其显式转换为void*,例如std::cout &lt;&lt; static_cast&lt;const void*&gt;(arr[i])

【讨论】:

    【解决方案2】:

    这里的pInt[n] 是一个int*,或者一个整数指针。您正在分配一个地址 (&amp;i),因此它会打印一个地址。

    如果您想打印该值,您需要执行*pInt[i]取消引用指针。

    【讨论】:

    • 当然你的解释是正确的,但可能 OP 的混淆起源于注意到 char * 也是地址。可能他们需要了解以空结尾的字符串是由cout 以特殊方式解释的。
    • @RobertoCaboni 我喜欢卡米尔对这方面问题的回答。
    • 很遗憾,因为你是第一个! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 2021-03-27
    • 2021-04-21
    • 1970-01-01
    • 2013-06-02
    相关资源
    最近更新 更多