【问题标题】:C++ setting char pointer to null [duplicate]C ++将char指针设置为null [重复]
【发布时间】:2013-06-04 08:03:05
【问题描述】:

在 Visual Studio 2012 中,我在搞乱指针,我意识到这个程序一直在崩溃:

#include <iostream>
using std::cout;
using std::endl;

int main ()
{
   const char* pointer = nullptr;

   cout << "This is the value of pointer " << pointer << "." << endl;

   return 0;
}

我的意图是将pointer 设置为nullptr,然后打印地址。即使程序可以编译,它也会在运行时崩溃。有人可以解释发生了什么吗?

另外,pointer*pointer 有什么区别?

【问题讨论】:

  • @jogojapan 还有很多问题的副本。

标签: c++ pointers nullptr


【解决方案1】:

您正在使用const char*,当在std::coutoperator &lt;&lt; 中使用时,它被解释为字符串。

将其转换为void* 以查看指针的值(它包含的地址):

cout << "This the value of pointer   " << (void*)pointer << "." << endl;

或者如果你想学究气:

cout << "This the value of pointer   " << static_cast<void*>(pointer) << "." << endl;

LIVE EXAMPLE

【讨论】:

  • 太棒了,非常感谢!有没有办法打印出内存位置而不必类型转换指针?
  • static_cast&lt;void *&gt;(pointer) 会更优雅。
  • @TadeuszKopec 和迂腐。 :)
  • static_cast&lt;void*&gt;(pointer) 一点都不优雅,但它是正确的方式
【解决方案2】:

虽然你可以像已经建议的那样做cout &lt;&lt; "Pointer is " &lt;&lt; (void*)pointer &lt;&lt; ".\n";,但我觉得在这种情况下,做它的“C 方式”更漂亮(没有强制转换)并且更具可读性:printf("Pointer is %p\n",pointer);

【讨论】:

  • 正式地说,这也需要一个演员表,因为%p 转换需要void*。然而,在 C 中,char*void* 需要具有相同的表示形式,而且我几乎可以肯定在 C++ 中也是如此,因此,尽管存在形式上的错误,但在获得 @987654327 时,没有任何明智的实现可以做一些意想不到的事情@ 用于%p 转换[用于“明智”的价值观,不包括故意惩罚遗漏演员的人]。它可以“诚实地”中断指向除字符类型之外的其他类型的指针,因为它们不需要具有相同的表示。
猜你喜欢
  • 2014-07-30
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多