C语言中结构体的二级指针

C语言中结构体嵌套二级指针申请内存。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct Teacher {
char *name;
char **students;
}Teacher;

static void allocateSpace(struct Teacher ***teachers) {
if (teachers == NULL) {
return;
}

//开辟内存
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_Student_%d", ts[i]->name, j + 1);
}
}

*teachers = ts;
}

static void printTeachers(struct Teacher **pArray) {
if (pArray == NULL) {
return;
}

for (int i = 0; i < 3; i++) {
printf("%s\n", pArray[i]->name);
for (int j = 0; j < 4; j++) {
printf(" %s\n", pArray[i]->students[j]);
}
}

}

static void freeSpace(struct Teacher **pArray) {
if (pArray == NULL) {
return;
}

for (int i = 0; i < 3; i++) {
//先释放老师姓名
if (pArray[i]->name != NULL) {
free(pArray[i]->name);
pArray[i]->name = NULL;
}

//释放学生姓名
for (int j = 0; j < 4; j++) {
if (pArray[i]->students[j] != NULL) {
free(pArray[i]->students[j]);
pArray[i]->students[j] = NULL;
}
}
//释放学生的数组
if (pArray[i]->students != NULL) {
free(pArray[i]->students);
pArray[i]->students = NULL;
}

//释放老师
if (pArray[i] != NULL) {
free(pArray[i]);
pArray[i] = NULL;
}

}


//释放老师数组
if (pArray != NULL) {
free(pArray);
pArray = NULL;
}

}

static void test01() {
struct Teacher **pArray = NULL;
//开辟内存
allocateSpace(&pArray);

//打印数组
printTeachers(pArray);

//释放数组
freeSpace(pArray);
pArray = NULL;

}


int main01() {

test01();

system("pause");
return EXIT_SUCCESS;