关于指针与引用的一些关系

1.交换指针的值

#include<iostream>
using namespace std;
void pr(int *&a, int *&b)//这里如果是指针的话,只是拷贝,不会交换指针的值
{
	int*c = a;
	a = b;
	b = c;
	c = NULL;
}
void pr1(int **a,int **b)//利用2重指针交换指针.
{
	int *c = *a;
	*a = *b;
	*b = c;
	c = NULL;
}
void main()
{
	int a = 10;
	int b = 15;
	int *p = &a;
	int *p1 = &b;
	pr(p, p1);
	cout << *p << " " << *p1 << endl;
	pr1(&p, &p1);
	cout << *p << " " << *p1 << endl;



	system("pause");
}

2.关于数组的形参传递

#include<iostream>
using namespace std;
void pr(int a[])
{
	cout << a[0] << endl;
}
void pr1(int *p)
{
	cout << p[0] << endl;
}
void pr2(int a[10])//注意,这里只是我们期望的数组元素为10,你并不清楚到底有多少。
{
	cout << a[0] << endl;

}
void pr3(int (&a)[10])//只能绑定确定数组的大小
{
	cout << a[0] << endl;
}
void pr4(int a[][10])//二维数组
{
	cout << a[0][0] << endl;
}

void pr6(int(*p)[10])//指向数组的指针,该数组是由10个数组构成的数组
{
	cout << *p[0] << endl;
}
void main()
{
	int a[10] = { 1, 0 };
	int b[2][10] = { 1 };
	pr(a);
	pr1(a);
	pr2(a);
	pr3(a);
	pr4(b);
	pr6(b);

	system("pause");
}

我是大一的初学者,最近创了一个c/c++的交流群,欢迎加入共同进步

群号:1011985882

猜你喜欢

转载自blog.csdn.net/qq_43702629/article/details/89435278