Structure nested secondary pointer

 

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

struct Teacher{

	char* name;
	char** students;
};

void allocateSpace(struct Teacher*** teachers)
{
	int i,j;
	struct Teacher** pArray = (struct Teacher**)malloc(sizeof(struct Teacher*)* 3);

	for(i = 0;i < 3;i++)
	{
		//给每个老师分配空间
		pArray[i] = (struct Teacher*)malloc(sizeof(struct Teacher));

		//给每个老师姓名 分配空间 并赋值
		pArray[i]->name = (char*)malloc(sizeof(char)*64);
		sprintf(pArray[i]->name,"Teacher_%d",i + 1);

		//给每个老师带的学生数组 分配空间
		pArray[i]->students = (char**)malloc(sizeof(char*)*4); //说明学生数组长度为4

		//给某老师的4个学生分别分配内存 并赋值
		for(j = 0;j < 4; j++)
		{
			pArray[i]->students[j] = (char*)malloc(sizeof(char)* 64);
			sprintf(pArray[i]->students[j],"%s_student_%d",pArray[i]->name ,j + 1);
		}

	}
	*teachers = pArray;
	
}
void printArray(struct Teacher** arr,int len)
{
	int i,j;
	for(i = 0;i < len;i++)
	{
		printf("老师姓名:%s\n",arr[i]->name);
		for(j = 0; j < 4; j++)
		{
			printf("    %s\n",arr[i]->students[j]);
		}
	}
}
void freeSpace(struct Teacher** pArray,int len)
{
	int i,j;
	//释放老师姓名空间
	for(i = 0; i < len; i++)
	{
		if(pArray[i]->name != NULL)
		{
			free(pArray[i]->name);
			pArray[i]->name = NULL;
		}
		//释放老师的每个学生的空间
		for(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;
	}
	
}
void test01()
{
	struct Teacher** pArray = NULL;//(struct Person**)malloc(sizeof(struct Person*)* 3);

	//分配内存
	allocateSpace(&pArray);

	//打印数组
	printArray(pArray,3);

	//释放内存
	freeSpace(pArray,3);
}
int main()
{
	test01();
	return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_42596333/article/details/104507730