1. 程式人生 > >結構體包含二級指標和二級指標記憶體的申請與釋放問題

結構體包含二級指標和二級指標記憶體的申請與釋放問題

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

typedef struct Teacher 
{
	char name[20];//20 記憶體塊 已分配
	int age;//4
	char *alisname;//4 只分配4個位元組的記憶體 
	char **stunames;//規定一個研究生導師帶4名學生
	
}Teacher;


void printTeacher(Teacher *arr,int num)
{
	int i;
	for (i=0;i<num;i++)
	{
		printf("age:%d\n",arr[i].age);
	}
}
void sortTeacher(Teacher *arr,int num)
{
	int i,j;
	Teacher tmp ;

	for (i=0;i<num;i++)
	{
		for (j=i+1;j<num;j++)
		{
			if (arr[i].age>arr[j].age)
			{
				tmp = arr[i];
				arr[i] = arr[j];
				arr[j] = tmp;
			}
		}
	}
}
//通過函式引數返回
int createTeacher2(Teacher**tea,int Tnum,int Snum )
{
	Teacher *tmp;
	int ret = 0,i,j;
	char **p=NULL;
	tmp =(Teacher*)malloc(sizeof(Teacher)*Tnum);
	//printf("sizeof(Teacher):%d\n",sizeof(Teacher));//
	if (tmp == NULL)
	{
		ret = -1;
		return ret;
	}
	memset(tmp,0,sizeof(Teacher)*Tnum);
	for (i=0;i<Tnum;i++)
	{
		//為一級指標指向的分配記憶體空間
		tmp[i].alisname = (char*)malloc(60);
		//為二級指標指向的分配記憶體空間 
		p = (char**)malloc(Snum*sizeof(char*));
		for (j=0;j < Snum;j++)
		{
			p[j] = (char *)malloc(30);
		}
		tmp[i].stunames = p;
	}
	*tea = tmp;
	return ret;
}
void freeTeacher(Teacher *p,int Tnum,int Snum)
{
	int i,j;
	char **tmp;
	if (p==NULL)
	{
		return ;
	}
	for (i = 0;i<Tnum;i++)
	{
		//釋放一級指標
		if (p[i].alisname!=NULL)
		{
			free(p[i].alisname);
		}
		//釋放二級指標
		tmp = p[i].stunames;
		if (tmp!=NULL)
		{
			for (j = 0;j < Snum; j++)
			{
				if (tmp[j]!=NULL)
				{
					free(tmp[j]);
					tmp[j] = NULL;
				}
			}
			free(tmp);
			tmp = NULL;
		}
	}
	free(p);
}
int main()
{
	int i,j;
	Teacher *Array;  
	int teahcerNum = 3;//老師的數量
	int studentNum = 4;//一位老師的學生的數量
	createTeacher2(&Array,teahcerNum,studentNum);  

	for (i=0;i<teahcerNum;i++)  
	{  
		
		printf("\nPlease inter teacher's name:");//想指標指向的  
		scanf("%s",Array[i].name);  
		printf("\nPlease inter teacher's age:");  
		scanf("%d",&Array[i].age);  
		printf("\nPlease inter teacher's alisename:");  
		scanf("%s",Array[i].alisname);  
		
		for (j=0;j < studentNum;j++)
		{
			printf("\nPlease inter teacher's students'name:");
			scanf("%s",Array[i].stunames[j]);  
		}
	}  
	freeTeacher(Array,teahcerNum,studentNum);
	system("pause");
	return;
}