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++基础知识 - 空指针和坏指针的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程