#include <iostream>
using namespace std;
struct Teacher
{
char name[64];
int age;
};
//在被调用函数 获取资源
int getTeacher(Teacher **p)
{
if (p == NULL)
{
return - 1;
}
Teacher *tmp = NULL;
tmp = (Teacher*)malloc(sizeof(Teacher));
if (tmp == NULL)
{
return -2;
}
tmp->age = 20;
*p = tmp;
}
int getTeacher1(Teacher*& p)
{
//给p赋值,相当于给main函数中的pt赋值
p = (Teacher*)malloc(sizeof(Teacher));
if (p == NULL)
{
return -1;
}
p->age = 30;
}
void FreeTeacher(Teacher* tmp)
{
if (tmp == NULL)
{
return;
}
free(tmp);
}
void main()
{
Teacher *pt = NULL;
//C语言中的二级指针
getTeacher(&pt);
cout << "age:" << pt->age << endl;
FreeTeacher(pt);
//C++中的引用(指针引用)
getTeacher1(pt);
cout << "age:" << pt->age << endl;
FreeTeacher(pt);
system("pause");
}
原文地址:https://www.cnblogs.com/Yu-Weijie/p/11434230.html