C ++ pointer references and pointers to pointers transport structures
#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);
}
Renderings: