C++将char指针设置为null

Bbv*_*ghe 3 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;

   }
Run Code Online (Sandbox Code Playgroud)

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

另外,pointer和的区别是什么 *pointer

Mar*_*cia 7

你正在使用一个const char*,当在std::cout's 中使用时operator <<,被解释为一个字符串.

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

cout << "This the value of pointer   " << (void*)pointer << "." << endl;
Run Code Online (Sandbox Code Playgroud)

或者如果你想变得迂腐:

cout << "This the value of pointer   " << static_cast<void*>(pointer) << "." << endl;
Run Code Online (Sandbox Code Playgroud)

现场例子

  • 关于`static_cast <void*>(指针)`没有什么优雅的,但这是正确的方法 (3认同)