C++工作笔记-对二级指针的进一步理解(函数的参数使用二级指针,从而操作原数据)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq78442761/article/details/82704202

二级指针不仅仅可以表示一个二维表(在邻接表里面用得比较多)!

当参数是一级指针的时候得到了是指向了同一个地址!

但参数是二级指针却有不同的效果!

如下代码:

main.cpp

#include<iostream>
using namespace std;

void getNewField(int *ptr){
	cout<<"&ptr address:"<<&ptr<<endl;
	cout<<"*ptr new before address:"<<ptr<<endl;
	ptr=new int(100);
	cout<<"*ptr new after address:"<<ptr<<endl;
}

void main(){
	int *ptrValue=NULL;
	cout<<"getNewField called befroe *ptrValue address:"<<ptrValue<<endl;
	cout<<"&ptrValue address:"<<&ptrValue<<endl;
	getNewField(ptrValue);
	cout<<"getNewField called after *ptrValue address:"<<ptrValue<<endl;
	cout<<"*ptrValue:"<<*ptrValue<<endl;	//no value, so application crash !
	getchar();
}

运行截图如下:

这里的参数相当于:

int *ptr=ptrValue;

他们仅仅是只指向了同一个地址!

使用二级指针可以达到我们想要的效果,代码如下:

#include<iostream>
using namespace std;

void getNewField(int **ptr){
	cout<<"&ptr address:"<<&ptr<<endl;
	cout<<"*ptr new before address:"<<ptr<<endl;
	*ptr=new int(100);
	cout<<"*ptr new after address:"<<ptr<<endl;
}

void main(){
	int *ptrValue=NULL;
	cout<<"getNewField called befroe *ptrValue address:"<<ptrValue<<endl;
	cout<<"&ptrValue address:"<<&ptrValue<<endl;
	getNewField(&ptrValue);
	cout<<"getNewField called after *ptrValue address:"<<ptrValue<<endl;
	cout<<"*ptrValue:"<<*ptrValue<<endl;
	getchar();
}

运行截图如下:

不会崩溃了,还能获取到值!

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/82704202