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)
我的意图是在设置pointer到null,然后打印地址.即使程序编译,它也会在运行时崩溃.有人可以解释发生了什么吗?
另外,pointer和的区别是什么 *pointer
你正在使用一个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)