结构体做函数参数(二)
作者:互联网
结构体中含有一维指针的内存分配和释放
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct Teacher { char name[64]; char *alisname; int age; int id; }Teacher; void printTeacher(Teacher *array,int num) { int i = 0; for (; 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[j]; array[j] = array[i]; array[i] = tmp; } } } } int createTeacher( Teacher **pT, int num) { int i = 0 ; Teacher *tmp = NULL; tmp = (Teacher *)malloc(num * sizeof(Teacher)); if (NULL == tmp) { return 0; } memset(tmp,0,sizeof(Teacher)*num); for (i = 0; i < num; i++) { tmp[i].alisname = (char *)malloc(60); } *pT = tmp; return 0; } void FreeTeacher(Teacher *p, int num) { int i = 0; if (p == NULL) { return ; } for (i = 0; i < num; i++) { if (p[i].alisname != NULL) { free(p[i].alisname); } } free(p); } int main() { int ret = 0; int i = 0; int num = 3; Teacher *pArray = NULL; ret = createTeacher(&pArray,num); if (ret != 0) { printf("func createTeacher() err : %d\n",ret); return ret; } for(i = 0; i < num; i++) { printf("\nplease enter age:"); scanf("%d",&(pArray[i].age)); printf("\nplease enter name:"); scanf("%s",(pArray[i].name)); printf("\nplease enter alias:"); scanf("%s",(pArray[i].alisname)); } printTeacher(pArray,num); sortTeacher(pArray,num); printf("after sort\n"); printTeacher(pArray,num); FreeTeacher(pArray,num); return 0; }
标签:tmp,体做,int,pArray,函数参数,num,array,Teacher,结构 来源: https://www.cnblogs.com/wanghao-boke/p/11783784.html