指针的引用

会有一股神秘感。 提交于 2020-02-08 14:33:09
#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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!