空指针异常(int Vs char)

时间:2016-05-13 04:31:38

标签: c++ pointers

计划1:

#include <iostream>
using namespace std;
int main ()
{
   int  *ptr = NULL;
   cout << "The value of ptr is " << ptr ;
   return 0;
}

计划2:

#include <iostream>
using namespace std;
int main ()
{
   char  *ptr = NULL;
   cout << "The value of ptr is " << ptr ;
   return 0;
}

问题是,在程序1中,输出稳定为:

  The value of ptr is 00000000

虽然在程序2中,我使用了char指针而不是int指针,它给了我一个例外。

任何人都可以帮助我理解吗?

1 个答案:

答案 0 :(得分:3)

因为&lt;&lt;运算符不是在第一个程序中取消引用int *,它只是将指针的值打印为0.但是在第二个程序中&lt;&lt;运算符正试图将指针取消引用为一个崩溃的字符串。

相关问题