c語言——結構體嵌套二級指針
如果一個結構體內嵌套二級指針了二級指針,這裏的students爲二級指針,也對應了一對多的關係,一個老師,多個學生。
struct Teacher
{
char *name;
char **students;
};
我們知道,二級指針指向一級指針的地址,三級指針指向二級指針的地址
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 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;
}
運行
Teacher_1
Teacher_1_Stu_1
Teacher_1_Stu_2
Teacher_1_Stu_3
Teacher_1_Stu_4
Teacher_2
Teacher_2_Stu_1
Teacher_2_Stu_2
Teacher_2_Stu_3
Teacher_2_Stu_4
Teacher_3
Teacher_3_Stu_1
Teacher_3_Stu_2
Teacher_3_Stu_3
Teacher_3_Stu_4