一段代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning (disable:4996)

typedef struct teacher {
	char name[20];
	int age;
	char **student;
}teacher;

void teacherSort(teacher *p, int n) { //选择法实现排序
	if (p == NULL) return;
	int i, j;
	teacher tmp;
	for(i=0;i<n-1;i++)
		for (j = i + 1;j < n;j++) {
			if (strcmp(p[i].name, p[j].name) > 0) {
				tmp = p[i];
				p[i] = p[j];
				p[j] = tmp;
			}
		}
}

int getTeacher(teacher **p, int n) { //为结构体数组分配空间
	if (p == NULL) return -1;
	teacher *tmp = (teacher *)malloc(sizeof(teacher)*n); 
	if (!tmp)return -1;
	int i, j;
	for (i = 0;i < n;i++) {
		char **ptmp = (char **)malloc(sizeof(char *) * 3);
		if (!ptmp) return -1;  //这里有个问题,以前分配的内存无法释放
		for (j = 0;j < 3;j++)
			ptmp[j] = (char *)malloc(20); //为每个学生分配20个字节的空间
		tmp[i].student = ptmp;
	}
	*p = tmp;
	return 0;
}

void freeMem(teacher *p, int n) { //还能传送二级指针,最后通过*p=tmp将结构数组置为NULL
	int i, j;
	for (i = 0;i < n;i++) {
		if (p[i].student) {
			char **ptmp = p[i].student;
			for (j = 0;j < 3;j++)
				if (!ptmp[j]) free(ptmp[j]);
			p[i].student = NULL;
		}
	}
	free(p);
}

int main() {
	teacher *t = NULL;
	int n;
	printf("print how many teacher:");
	scanf("%d", &n);
	int ret = getTeacher(&t, n);
	if (ret != 0) return -1;
	int i, j;
	char **ptmp = NULL;
	for (i = 0;i < n;i++) //输入数据
	{
		printf("input age,name and 3 student name\n");
		scanf("%d", &t[i].age);
		scanf("%s", t[i].name);
		ptmp = t[i].student;
		for (j = 0;j < 3;j++)
			scanf("%s", ptmp[j]);
	}

	teacherSort(t, n);

	for (i = 0;i < n;i++) { //输出数据
		printf("\n==========Print=========\n");
		printf("age:%d\n", t[i].age);
		printf("name:%s\n", t[i].name);
		ptmp = t[i].student;
		for (j = 0;j < 3;j++)
			printf("student name:%s\n", ptmp[j]);
	}

	system("pause");

}

1.主调函数定义一个指针变量,在被调函数分配内存,通过指针返回分配内存空间的首地址

2.结构体中嵌套二级指针,通过定义一个二级指针来操作,最后把二级指针传递给结构体中的二级指针

猜你喜欢

转载自blog.csdn.net/aabb7012086/article/details/81914340