空指针和野指针
空指针:指针变量指向内存编号位0的空间
用途:初始化指针变量
注意:空指针指向的内存是不可访问的
示例(空指针):
#include <iostream>
using namespace std;
int main() {
//空指针
//1.空指针用于给指针变量初始化
int* p = NULL;
//2.空指针是不可访问的
//* p = 100;这是错误的
//0~255之间的内存编号是系统占用的所以不可以访问
cout << "sizeof(int *) = " << sizeof(int*) << endl;
cout << "sizeof(float *) = " << sizeof(float*) << endl;
cout << "sizeof(double *) = " << sizeof(double*) << endl;
cout << "sizeof(char *) = " << sizeof(char*) << endl;
system("pause");
return 0;
}
野指针:指针变量指向非法的内存空间
示例(野指针)
#include <iostream>
using namespace std;
int main() {
//野指针
//在程序中避免出现野指针
int* p = (int*)0x1100;
cout << *p << endl;
system("pause");
return 0;
}
会出问题