结构体-内涵二级指针操作

#define _CRT_SECURE_NO_WARNINGS
#include
#include

typedef struct _Teacher
{
	char name[64];
	int age;
	char *title;
	char **pStd;//学生
}Teacher;

//打开内存
Teacher *createMem(int len)
{
	int i = 0,j = 0;
	Teacher *pArray = NULL;
	pArray = (Teacher *)malloc(4 * sizeof(Teacher));//老师的定义
	//定义职位
	for (i = 0; i < len; i++)
	{
		pArray[i].title = (char *)malloc(100);
	}
	//学生
	
	for (i = 0; i < len; i++)
	{
		char **pA = NULL;
		pA = (char **)malloc(4*sizeof(char *));
		//pArray[i].pStd = pA;//挂上来
		//理解错误
		for (j = 0; j < len; j++)
		{
			pA[j] = (char *)malloc(120);
		}
		pArray[i].pStd = pA;
	}
	return pArray;
}

//打印数据
int printfArr(Teacher *p, int len)
{
	if (p == NULL)
	{
		return -1;
	}
	for (int i = 0; i < len; i++)
	{
		printf("老师名字=%s,老师年纪%d,老师职称%s\n", p[i].name, p[i].age, p[i].title);
		printf("学生信息\n");
		for (int j = 0; j < len; j++)
		{
			printf("学生账号%s\n", p[i].pStd[j]);
		}
	}
	return 0;
}

int main()
{

	Teacher *pArr = NULL;
	pArr = createMem(3);
	if (pArr == NULL)
	{
		return -1;
	}

	for (int i = 0; i < 3; i++)
	{
		printf("第%d老师的姓名:", i + 1);
		scanf("%s", pArr[i].name);
		printf("第%d老师的年纪:", i + 1);
		scanf("%d", &pArr[i].age);
		printf("第%d老师的职称:", i + 1);
		scanf("%s", pArr[i].title);
		for (int j = 0; j < 3; j++)
		{
			printf("第%d学生的职称:", j + 1);
			scanf("%s", pArr[i].pStd[j]);
		}
	}
	printfArr(pArr,3);

	system("pause");
	return 0;
}

你可能感兴趣的:(C++)