【C语言提高38】结构体套一级指针

//结构体数组  3  输入老师年龄  排序

#include
#include
#include
#include

typedef struct teacher
{
	char name[64];
	char*alisname; //分配了四个字节的内存   需要显式的分配内存  嵌套套一级指针
	int age;
	int id;
}teacher;

void printfTeacher(teacher*array, int num)
{
	int i = 0;
	for (i = 0;i < num;i++)
	{
		printf("age:%d\n", (array[i].age));
	}
}

void sortTeacher(teacher*array, int num)
{
	int i, j;
	teacher tmp;
	for (i = 0;i < num;i++)
	{
		for (j = i + 1;j < num;j++)
		{
			if (array[i].age > array[j].age)
			{
				tmp = array[i];
				array[i] = array[j];
				array[j] = tmp;
			}
		}
	}
}


int createTeacher(teacher**pT, int num)
{
	int i = 0;
	teacher*tmp = NULL;
	tmp = (teacher*)malloc(sizeof(teacher)*num);//teacher Array[3];
	if (tmp == NULL)
	{
		return -1;
	}
	memset(tmp, 0, sizeof(teacher)*num);//刚分配完后 立马初始化

	for (i = 0;i < num;i++)
	{
		//malloc一级指针
		tmp[i].alisname = (char*)malloc(60);//指针明确指向  显式的分配内存
	}


	//pT二级指针  *pT就是一级指针  也就是pArray的地址
	*pT = tmp;//二级指针  形参 去间接修改实参的值
	return 0;
}

void freeTeacher(teacher*p, int num)
{
	if (p == NULL)
	{
		return;
	}
	for (int i = 0; i < num; i++)
	{
		if (p[i].alisname != NULL)
		{
			free(p[i].alisname);
		}
	}
}


void main41()
{
	int ret;
	int i = 0;
	int num = 3;
	teacher*pArray = NULL;
	ret = createTeacher(&pArray, num);
	if (ret != 0)
	{
		printf("funerr_createTeacer()");
		return;
	}

	for (i = 0; i < num; i++)
	{
		printf("\nplease enter age:");
		scanf_s("%d", &(pArray[i].age));

		printf("\nplease enter name:");
		scanf_s("%s", pArray[i].name);  //向指针所指向的内存空间拷贝数据

		printf("\nplease enter alias:");
		scanf_s("%s", pArray[i].alisname);//向指针所指向的内存空间拷贝数据
	}



	printfTeacher(pArray, num);

	sortTeacher(pArray, num);

	printf("排序之后\n");

	printfTeacher(pArray, num);



	printf("hehehe\n");
	system("pause");
	return;
}

你可能感兴趣的:(C语言提高)