C++基础——C++指针的引用

指针的引用:

int*p1;
int fun(int*& tmp)
{
    tmp// int*
}

代码示例:

#include

using namespace std;
struct Teacher
{
	char name[64];
	int age;
};

int getTeacherAge(Teacher** p)
{
	Teacher* tmp = (Teacher*)malloc(sizeof(Teacher));// 在堆上开辟空间
	if (!tmp)
	{
		return -1;
	}
	if (!p)
	{
		return -1;
	}

	tmp->age = 34;
	*p = tmp;// p为二级指针,*p为一级指针

}
//指针的引用,作为函数参数
void getTeacherAge2(Teacher* &p)//Teacher *&p;
{
	p = (Teacher*)malloc(sizeof(Teacher));
	
	p->age = 56;
	//p->name = { 'L', 'i' };
}
//释放堆区域
void freeTeacher(Teacher* p)
{
	if (p)
	{
		free(p);
	}
}
void main()
{
	Teacher* mT1 = NULL;

	getTeacherAge(&mT1);// 二级指针,一级指针的地址值
	cout << "mT1->age: " << mT1->age << endl;
	free(mT1);

	getTeacherAge2(mT1);
	cout << "mT1->age: " << mT1->age << endl;
	free(mT1);

	system("pause");
}

结果:
C++基础——C++指针的引用_第1张图片

你可能感兴趣的:(C++,C++基础补充,指针的引用,c++)