头文件:
#include<stdio.h> #include<stdlib.h> #include <string.h>
全局变量:
const int t_length = 3; typedef struct Teacher{ int id; char name[64]; char *alis; int age; }Teacher;
函数原型:
void createTeahcer(Teacher **ppt,int num); //给结构数组分配内存 void freeTeacher(Teacher *pt, int num); //释放内存 void sortTeacher(Teacher *pt, int num); //排序数组 void printTeacher(Teacher *pt, int num); //遍历数组
实现方法:
void createTeahcer(Teacher **ppt,int num){ int i; Teacher *temp; temp = (Teacher *)malloc(sizeof(Teacher) * num); for(i = 0; i < num; ++i){ temp[i].alis = (char *)malloc(sizeof(char) * 64); } *ppt = temp; } void freeTeacher(Teacher *pt, int num){ int i; if(pt != NULL){ for(i = 0; i < num; ++i){ if(pt[i].alis != NULL){ free(pt[i].alis); } } free(pt); } } void sortTeacher(Teacher *pt, int num){ int i, j; Teacher temp; for(i = 0; i < num; ++i){ for(j = i + 1; j < num; ++j){ if(pt[j].age < pt[i].age){ temp = pt[j]; pt[j] = pt[i]; pt[i] = temp; } } } } void printTeacher(Teacher *pt, int num){ int i; printf(" "); for(i = 0; i < num; ++i){ printf("学号:%d 姓名:%s 别名:%s 年龄:%d ", pt[i].id, pt[i].name, pt[i].alis, pt[i].age); } }