结构体嵌套二级指针的使用
Note:
对于结构体嵌套二级指针,务必注意在开辟结构体空间后对于结构体内部指针的操控。
以及对结构体内部指针数组(二级指针)指向的指针空间进行开辟空间。
再有就是对于手动开辟的空间进行一一释放,养成良好的Coding习惯!
运行环境:Ubuntu18.04 GNU GCC/CLION
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Teacher
{
char *name;
char **student;
};
void freePArray(struct Teacher **pArray)
{
if (!pArray)
{
return;
}
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
if (!pArray[i]->student[j])
{
return;
}
free(pArray[i]->student[j]);
pArray[i]->student[j] = NULL;
}
free(pArray[i]->student);
pArray[i]->student = NULL;
free(pArray[i]->name);
pArray[i]->name = NULL;
free(pArray[i]);
pArray[i] = NULL;
}
}
void test01()
{
struct Teacher **pArray = malloc(sizeof(struct Teacher *) * 3);
if (!pArray)
{
return;
}
for (int i = 0; i < 3; ++i)
{
pArray[i] = malloc(sizeof(struct Teacher));
pArray[i]->name = malloc(sizeof(char) * 21);
sprintf(pArray[i]->name, "Teacher_%d", i + 1);
pArray[i]->student = malloc(sizeof(char *) * 4);
for (int j = 0; j < 4; ++j)
{
pArray[i]->student[j] = malloc(sizeof(char) * 21);
sprintf(pArray[i]->student[j], "Student_%d", j + 1);
}
}
for (int i = 0; i < 3; ++i)
{
printf("%s\n", pArray[i]->name);
for (int j = 0; j < 4; ++j)
{
printf("\t%s\n", pArray[i]->student[j]);
}
}
freePArray(pArray);
free(pArray);
pArray = NULL;
}
int main(int argc, char const *argv[])
{
test01();
return 0;
}
Picture: