指针和引用的区别和联系

版权声明:个人爱好,可随便转载 https://blog.csdn.net/qq_43528087/article/details/88935120

指针的优势

<1>动态分配内存
<2>可以实现址传递
<3>方便处理字符串
<4>高效的使用数组

指针和引用的区别

本质区别:指针是地址,引用是别名
1. 指针可以改变它所指向的值,而引用一旦与某个变量绑定后就不再改变
2. 系统给指针分配内存空间,不给引用分配内存空间
3. 引用不能为空,指针可以为空

代码如下:

#include <iostream>
using namespace std;

int main()
{
	int x = 3;
	int &y = x; //定义x的一个引用y
	int *p = &x;//指向x的指针p

	cout << "x=" << x << " " << "y=" << y << endl;
	cout << &x << endl;
	cout << &y << endl;
	cout << p << endl;
	cout << &p << endl;

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43528087/article/details/88935120