一重指针、二重指针做函数参数的深刻分析(虽然很基础,但要深刻理解)

一重指针做函数参数

#include<iostream>
using namespace std;
void change(int *p)
{
	*p = 20;
	p++;
	cout << p << endl;
}
int main() {
	int a = 10;
	int *pa = &a;
	change(pa);
	cout << pa << endl;
	cout << a << endl;
	system("pause");
	return 0;
}

在这里插入图片描述
首先弄清楚,无论怎么改程序,&a的值永远不会变,可别智障了!
分析:
change(pa)传参时,指针p申请内存空间,p的内存空间中存的是pa(pa和a的地址的值相同),所以说此时传入函数的是指针的copy。因此,在函数内改变指针p的值并不会影响pa(即p++执行完后p和pa的值不可能相等)。

二重指针做函数参数

如果要修改pa,那么修改如下:

void change(int **p)
{
	**p = 20;
	(*p)++;
	cout << *p << endl;
}
int main() {
	int a = 10;
	int *pa = &a;

	change(&pa);
	cout << pa << endl;
	cout << a << endl;

	system("pause");
	return 0;
}

在这里插入图片描述
分析:
change(&pa)传参时,二重指针p申请内存空间,p的内存空间中存的是指针pa的地址,所以说此时传入函数的是指针的地址的copy。此时,(*p)就是pa,两者完全等价。所以在函数内执行(*p)++,pa的值自然也会随之改变。

一重指针的引用做函数参数

使用一重指针的引用做函数参数也修改pa(效果和二重指针做函数参数完全相同):

void change(int* &p)
{
	*p = 20;
	p++;
	cout << p << endl;
}
int main() {
	int a = 10;
	int *pa = &a;
	change(pa);
	cout << pa << endl;
	cout << a << endl;
	system("pause");
	return 0;
}

在这里插入图片描述

最后是一个实现二维数组动态分配的例子:

#include<iostream>
using namespace std;
int main()
{
	int m,n;
	cin >> m>>n;
	int **a = new int*[m];
	for (int i = 0; i < m; i++)
		a[i] = new int[n];//a[i]的类型是int*

	

	for (int i = 0; i < m; i++)
	{
		for (int j = 0; j < n; j++)
		{
			a[i][j] = i + j;
			cout << a[i][j] << "  ";

		}
			
		cout << endl;
	}

	for (int i = 0; i < m; i++)
		delete[] a[i];
	delete[]  a;
	system("pause");
	return 0;
}
#include<iostream>
using namespace std;
int main()
{

	char*p[3] = { "America","China","Itlay" };//指针数组,数组中的每个元素都是char*类型的
	char**q = p;
	cout << q[0][0] << endl;
	cout << q[1][0] << endl;
	cout << q[2][0] << endl;
	cout << q[0] << endl;
	cout << q[1] << endl;
	cout << q[2] << endl;
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值