#include <iostream>
#include <cstring>
using namespace std;
//指针的引用
struct teacher{
int id;
char name[64];
};
//使用二级指针生成和释放
int get_mem(teacher** tpp){
teacher* tp = NULL;
tp = (teacher*)malloc(sizeof(teacher));
if(tp==NULL){
return -1;
}
tp->id=10;
strcpy(tp->name,"hahah");
*tpp = tp;
return 0;
}
//释放
void free_teacher(teacher** tpp){
if(tpp==NULL){
return;
}
teacher* tp = *tpp;
if(tp!=NULL){
free(tp);
*tpp=NULL;
}
}
//使用引用生成和释放
int get_mem2(teacher* &tp){
tp = (teacher*)malloc(sizeof(teacher));
if(tp==NULL){
return -1;
}
tp->id=300;
strcpy(tp->name,"nanna");
return 0;
}
//释放
void free_teacher2(teacher* &tp){
if(tp!=NULL){
free(tp);
tp=NULL;
}
}
int main(){
teacher *tp = NULL;
get_mem(&tp);
cout<<"id: "<<tp->id<<" name: "<<tp->name<<endl;
free_teacher(&tp);
cout<<"-------------------"<<endl;
get_mem2(tp);
cout<<"id: "<<tp->id<<" name: "<<tp->name<<endl;
system("pause");
return 0;
}
来源:CSDN
作者:从前,有个傻子........
链接:https://blog.csdn.net/weixin_41377572/article/details/104221724