【问题标题】:C++ Printing value of pointer gives strange result指针的 C++ 打印值给出了奇怪的结果
【发布时间】:2011-09-20 10:11:12
【问题描述】:

当我编译并运行这个 C++ 代码时,我没有得到预期的输出。

#include <iostream>
using namespace std;

int main()
{
    int * i = new int;
    long * l = new long;
    char * c = new char[100];
    float * f = new float[100];

    cout << "i " << i << endl;
    cout << "l " << l << endl;
    cout << "c " << c << endl;
    cout << "f " << f << endl;


    delete i;
    delete l;
    delete []c;
    delete []f;

    cin.get();
    return 0;
}

在 unix 机器上我得到

i 0x967f008
l 0x967f018
c
f 0x967f090

在 Windows 机器上,c 的值打印为一行随机字符。

请有人解释为什么它没有正确打印 char 数组的指针。

谢谢

【问题讨论】:

    标签: c++ pointers


    【解决方案1】:

    operator &lt;&lt; for std::ostreamstd::wostream 以特殊方式定义用于 char 指针(char*const char*wchar_t*const wchar_t* 以打印出以 null 结尾的字符串。这使您可以写

    const char* str = "Hello, World";
    std::cout << str;
    

    并在您的标准输出上看到一个漂亮的字符串。

    要获取指针值,请转换为void *

    std::cout << static_cast<void*>(c)
    

    【讨论】:

      【解决方案2】:

      operator&lt;&lt;char* 重载。它会认为您正在尝试打印 C 风格的字符串,并打印所有字符,直到找到 0x00。由于您没有初始化分配的内存,它会打印出随机垃圾。

      【讨论】:

      • C++ 的做法是什么:(void *)c?
      • 那就是reinterpret_cast&lt;void*&gt;(c)
      • @hexa:虽然@Mat 的正确之处在于(void*)c 等同于reinterpret_cast&lt;void*&gt;(c),但C++ 方式static_cast&lt;void*&gt;(c);
      【解决方案3】:

      char * 实际上是一个 C 字符串。所以我猜它正在尝试将其打印为字符串。

      强制打印指针地址的一种方法是使用 printf:

      printf("%p\n", c);
      

      【讨论】:

        【解决方案4】:

        由于 c 指向的 char 中没有初始化,因此您转储了一些随机内存值,直到找到值为 0 的值。它有时会崩溃,直到您的可读内存完成时才找到零。在 Unix 和任何其他操作系统中,编写这样的代码也是被禁止的并且错误

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多