【问题标题】:C++ reinterpret_castC++ reinterpret_cast
【发布时间】:2025-12-19 06:05:11
【问题描述】:

在运行这个程序时:

#include <iostream>
int main()
{
char *name = "abc";
int i = reinterpret_cast<int>(name);
std::cout<<i<<std::endl;
return 0;
}

我得到以下输出:

4202656

这个数字代表什么?是内存地址吗?但是,内存地址是什么? “abc”不是作为字符数组存储在内存中的吗?

谢谢。

【问题讨论】:

  • reinterpret_cast 运算符生成一个新类型的值,该值具有与其参数相同的位模式。您使用的是哪个编译器? g++ 给出了一个错误的转换。
  • @DumbCoder。当我输入 char *name = "abc"; 时,我得到 same 输出

标签: c++ memory reinterpret-cast


【解决方案1】:

这是“abc”第一个字符的内存地址,所以是“a”。因为数组是指向数组第一个值的指针。
如果你这样做cout &lt;&lt; *(name++),通常会打印“b”。

所以当投射name时,你尝试投射指向“a”的地址

【讨论】:

    【解决方案2】:

    你可能想看看这个问题:casting via void* instead of using reinterpret_cast

    简短的回答是它可以是任何东西。

    【讨论】:

    • 标准确实说了。对于了解底层内存架构的人来说,结果应该不足为奇。 [注意:对于那些知道底层机器的寻址结构的人来说,这并不奇怪。 ——尾注]
    【解决方案3】:

    这可能是字符“a”的地址。
    虽然我不认为这是有保证的(即 int 可能不够长来保存地址)。

    【讨论】:

    • 约克。当我输入 char *name = "abc"; 时,我得到相同的输出
    • @user588855:不明白你的评论。这与您的代码相同。
    【解决方案4】:

    未定义。 sizeof(int) 可能不等于 sizeof(char*)。我不确定这里是否也适用严格的别名规则。

    然而,实际上,假设它们的大小确实相等(大多数 32 位平台),4202656 将表示数组中第一个字符的地址。我会这样做更干净:

    #include <iostream>
    int main()
    {
       const char *name = "abc"; // Notice the const. Constant string literals cannot be modified.
       std::cout << static_cast<const void*>(name) << std::endl;
    }
    

    【讨论】: