c语言 struct 二级指针,结构体嵌套二级指针

06147a41e7d1

画的.png

在结构体中嵌套二级指针

struct Teacher

{

char *name;

char **students;

};

如上的结构体 ,首先打算弄个Techears类数组 然后..这样就可以存储多个老师了

代码如下所示

主要的步骤

①首先在main中创建二级指针struct Teacher **teachers

②然后把传到给这个二级指针赋值 ret = allocateSpace(&teachers);

③在allocateSpace中采用指针间接赋值的方式

④然后赋值完成后 进行内存的释放(内存的释放从低级到高级 意思是在上方图中 后申请的先释放)

#define _CRT_SECURE_NO_WARNINGS

#include

#include

#include

struct Teacher

{

char *name;

char **students;

};

int allocateSpace(struct Teacher ***temp)

{

if (NULL == temp)

{

//错误码 不同错误码表示不同错误

return -1;

}

struct Teacher **ts = malloc(sizeof(struct Teacher *) * 3);

for (int i = 0; i < 3; ++i)

{

//给老师结构体指针分配空间

ts[i] = malloc(sizeof(struct Teacher));

//给老师名字分配空间

ts[i]->name = malloc(sizeof(char) * 64);

sprintf(ts[i]->name, "Teacher_%d", i + 1);

//给学生指针分配内存

ts[i]->students = malloc(sizeof(char *)* 4);

for (int j = 0; j < 4; ++j)

{

ts[i]->students[j] = malloc(sizeof(char) * 64);

sprintf(ts[i]->students[j],"%s_Stu_%d",ts[i]->name,j + 1);

}

}

*temp = ts;

return 0;

}

void printTeachers(struct Teacher **teachers)

{

if (NULL == teachers)

{

return;

}

for (int i = 0; i < 3; ++i)

{

printf("%s\n", teachers[i]->name);

for (int j = 0; j < 4; ++j)

{

printf(" %s\n",teachers[i]->students[j]);

}

}

}

void freeSpace(struct Teacher **teachers)

{

if (NULL == teachers)

{

return;

}

for (int i = 0; i < 3; ++i)

{

if (teachers[i] == NULL)

{

continue;

}

if (teachers[i]->name != NULL)

{

free(teachers[i]->name);

teachers[i]->name = NULL;

}

for (int j = 0; j < 4; ++j)

{

if (teachers[i]->students[j] != NULL)

{

free(teachers[i]->students[j]);

teachers[i]->students[j] = NULL;

}

}

free(teachers[i]->students);

teachers[i]->students = NULL;

free(teachers[i]);

teachers[i] = NULL;

}

free(teachers);

teachers = NULL;

}

void test()

{

struct Teacher **teachers = NULL;

int ret = 0;

ret = allocateSpace(&teachers);

if (ret < 0)

{

printf("allocateSpace 函数调用出错!\n");

return;

}

//打印老师及其学生信息

printTeachers(teachers);

//释放内存

freeSpace(teachers);

teachers = NULL;

}

int main(){

test();

system("pause");

return EXIT_SUCCESS;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值