码迷,mamicode.com
首页 > 其他好文 > 详细

C 结构体嵌套一级指针 二级指针 动态分配内存

时间:2016-05-12 16:53:16      阅读:387      评论:0      收藏:0      [点我收藏+]

标签:

#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//结构体嵌套一级指针 二级指针 动态分配内存
typedef struct _Teacher {
	int age;
	int id;
	char *title;
	char **pStuarray;
	char name[64];

}Teacher;
//打印结构体
void printfTeacher(Teacher *array,int num) {
	int i = 0;
	for ( i = 0; i < num; i++)
	{
		printf("%d\n", array[i].age);
		printf("%s\n",array[i].pStuarray[i]);
	}

}
//给结构体分配内存
Teacher* createTarray(int num) {
	int i = 0,j=0;
	Teacher* teacher;
	teacher = (Teacher*)malloc(sizeof(Teacher)*num);
	if (teacher!=NULL)
	{
		for ( i = 0; i < num; i++)
		{
			teacher[i].title = (char*)malloc(sizeof(char)*100);//结构体Teacher title分配内存
			char** ptmp = (char**)malloc(sizeof(char*)*num);//
			for ( j = 0; j < num; j++)
			{
				ptmp[i] = (char*)malloc(100);//
			}
			teacher[i].pStuarray = ptmp;
		}
	}
	return teacher;
}
//释放内存
void freeTeacher(Teacher* arrayT,int num) {
	int i = 0,j=0;
	if (arrayT!=NULL)
	{
		for (i = 0; i < num;i++) {
			if (arrayT[i].title != NULL) {
				free(arrayT[i].title);
			}
			if (arrayT[i].pStuarray!=NULL)
			{
				for (j = 0; j < num; j++)
				{
					free(arrayT[i].pStuarray[j]);
				}
			}
			free(arrayT[i].pStuarray);
		}

		free(arrayT);
	}

}

void main() {
	int i = 0,j=0;
	Teacher *pArray=NULL;
	int num = 1;
	pArray = createTarray(num);
	
	for (i = 0; i < num; i++)
	{
		printf(" %d---age?\n", i + 1);
		scanf("%d", &pArray[i].age);
		printf(" %d---title?\n", i + 1);
		scanf("%s", pArray[i].title);
		printf(" %d---name?\n", i + 1);
		scanf("%s", pArray[i].name);

		
		for (j = 0; j < num; j++)
		{
			printf(" ---student----%d\n",i+1);
			scanf("%s", pArray[i].pStuarray[j]);
		}
	}
	printfTeacher(pArray,num);
	
	freeTeacher(pArray, num);
	system("pause");
}

C 结构体嵌套一级指针 二级指针 动态分配内存

标签:

原文地址:http://blog.csdn.net/xielinhua88/article/details/51364623

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!