C++指针引用和指向指针的指针传输结构体

C++指针引用和指向指针的指针传输结构体

#include <iostream>
using namespace std;

struct teacher {
	int id;
	char name[64];	
};

int tea(struct teacher* &a) {//指针引用,a是c的别名
	
	a = (struct teacher*)malloc(sizeof(struct teacher));//a = 开辟的内存,相当于c开辟内存,在写入数据
	if (a == NULL)
	{
		return -1;
	}
	a->id = 100;
	strcpy_s(a->name, "礼仪");
	return 0;
}

int tea1(struct teacher **a) {//指向指针的指针指向a(函数的实参)指针的取地址
	struct teacher *t = NULL;//a=实参的取地址,&a是a(指向指针的指针)的取地址,*a是a指向内存的内容
	if (a==NULL)             
	{
		return -1;
	}
	
	t = (struct teacher*)malloc(sizeof(struct teacher));//理解为某指针指向某地址,指针t = 某指针
	       
	//cout << t << endl;//t是一个指针,指向在内存中开辟的一个地址,t=某地址
	//cout << &t << endl;//&t是t自己的取地址
	//cout << a << endl;//
	//cout << *a << endl;
	//cout << &a << endl;
	//cout << &(*a) << endl;
	t->id = 100;	
	strcpy_s(t->name, "哈哈");
	*a = t;
	return 0;
}

void rea1(struct teacher **a) {
	if (a==NULL)
	{
		return;
	}
	struct teacher* t = *a;
	if (t!=NULL)
	{
		free(t);//开辟内存,要释放
		*a = NULL;		
	}
}

void rea(struct teacher *&a) {
	if (a==NULL)
	{
		return;
	}
	else
	{
		free(a); //开辟内存,要释放
		a = NULL;
	}
}

void main() {
	struct teacher *c = NULL;//定义一个指针作传输体

	tea1(&c);
	cout << "id=" <<c->id<<"名字:"<< c->name << endl;//极有可能是*(c->id)
	rea1(&c);
	tea(c);
	cout<< "id=" <<c->id<<"名字:"<< c->name << endl;
	rea(c);
}


效果图:
在这里插入图片描述

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值