C++基础知识 - 空指针和坏指针
2022/1/17 11:34:40
本文主要是介绍C++基础知识 - 空指针和坏指针,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
空指针和坏指针
1. 什么是空指针? 空指针,就是值为 0 的指针。
(任何程序数据都不会存储在地址为 0 的内存块中,它是被操作系 统预留的内存块。)
int *p = 0; 或者 int *p = NULL; //强烈推荐
2. 空指针的使用
1)指针初始化为空指针, 目的就是, 避免访问非法数据。 int *select = NULL; 2)指针不再使用时, 可以设置为空指针 int *select = &xiao_long_lv; // select = NULL; 3)表示这个指针还没有具体的指向, 使用前进行合法性判断 int *p = NULL; 。。。。 if (p) { //p 等同于 p!=NULL //指针不为空,对指针进行操作 }
3. 坏指针
int *select; //没有初始化 情形一: cout<< "选择的是: " << *select << endl; 情形二: select = 100; cout<< "选择的是: " << *select << endl;
demo
#include <iostream> #include <Windows.h> using namespace std; int main(void) { int age1 = 22; int age2 = 21; int select; int* age = NULL; //指针指向NULL cout << "请选择: "; cin >> select; if (select == 22) { age = &age1; } else if (select == 21) { age = &age2; } if (age == NULL) { cout << "没有任何选择!" << endl; } else { cout << "选择的是: " << *age << endl; } system("pause"); return 0; }
这篇关于C++基础知识 - 空指针和坏指针的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03如何安装 App 并连接到飞牛 NAS?-icode9专业技术文章分享
- 2024-10-03如何安装飞牛 TV 并连接到影视服务器?-icode9专业技术文章分享
- 2024-10-03如何在PVE和ESXI上安装飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS安装系统异常情况处理-icode9专业技术文章分享
- 2024-10-03飞牛NAS如何创建存储空间?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS硬盘会自动休眠吗?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何安装飞牛影视和创建媒体库?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何为家人朋友开通影视账号?-icode9专业技术文章分享