结构体嵌套二级指针

结构体嵌套二级指针

typedef struct TEACHER

{

char Tname[30];

char** stu;

}Teacher;

void createTeacher(Teacher** teacher,int n,int m)

{

if(teacher==NULL)

{

return;

}

Teacher* tmp=(Teacher*)malloc(sizeof(Teacher)*n);

 

for(int i=0;i

{

sprintf(tmp[i].name,”%d_teacher”,i+1);

tmp[i].stu=(char**)malloc(sizeof(char*)*m);

for(int j=0;j

{

tmp[i].stu[j]=malloc(30);

sprintf(tmp[i].stu[j],”%d_students”,j+1);

}

}

*teacher=tmp;

}

void freemem(Teacher** teacher,int n,int m)//先释放二级指针,再释放一级指针

{

if(teacher==NULL)

return;

Teacher* tmp=*teacher;

for(int i=0;i

{

for(int j=0;j

{

free(tmp[i].stu[j]);

tmp[i].stu[j]=NULL;

}

}

free(tmp);

}

int main()

{

Teacher* p=NULL;

createTeacher(&p,2,3);

freemem(&p,2,3);

return 0;

}

你可能感兴趣的:(c语言)