C++ 将 char 指针设置为 null

标签 c++ pointers nullptr

<分区>

在 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;
}

我的意图是设置一个指向nullptr指针,然后打印地址。即使程序可以编译,它也会在运行时崩溃。谁能解释一下这是怎么回事?

还有,pointer*pointer 有什么区别?

最佳答案

您正在使用 const char*其中,在 std::cout 中使用时的 operator << , 被解释为字符串。

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

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

或者如果你想学究气:

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

LIVE EXAMPLE

关于C++ 将 char 指针设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16912645/

相关文章:

c++ - 关于cin/cout重载的简单问题

c - 如何在多维数组中添加数组?

c++ - 什么是 "Read Access Violation... was nullptr"?

c++ - "resurrect"(序列化/反序列化)std::map 的最快方法

c++ - 在 arm neon 中有效地计算两个不同的数字

c++ - 从命名对象的构造函数链式调用成员函数

c - C 中带有指针的这些 volatile 是什么意思?

c - c中的指针问题

由 nullptr 初始化的 C++11 自动变量

C++ gmock - 将空指针传递给 SaveArg 时会发生什么