1 #define _CRT_SECURE_NO_WARNINGS 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<string.h> 5 6 typedef struct Teacher 7 { 8 char name[64]; 9 int age; 10 int id; 11 }Teacher; 12 13 void printTeacher(Teacher *array, int num) 14 { 15 int i = 0; 16 //打印老師年齡 17 for (i = 0; i < num; i++) 18 { 19 //printf("age:%d\n", array[i].age); 20 printf("age:%d\n", (*(array + i) ).age); 21 //(array++)->age; 22 } 23 }//(*(array+i)).age 24 25 void sortTeacher(Teacher *array,int num) 26 { 27 int i, j; 28 Teacher tmp; 29 for (i = 0; i < num;i++) 30 { 31 for (j = i; j < num;j++) 32 { 33 if (array[i].age<array[j].age) 34 { 35 tmp = array[i]; 36 array[i] = array[j]; 37 array[j] = tmp; 38 } 39 } 40 } 41 } 42 43 44 Teacher * createTeacher(int num) 45 { 46 Teacher * tmp = NULL; 47 tmp = (Teacher*)malloc(sizeof(Teacher)*num); // Teacher Array[3] 48 if (tmp == NULL) 49 { 50 return NULL; 51 } 52 } 53 54 void FreeTeacher(Teacher *p) 55 { 56 if (p!=NULL) 57 { 58 free(p); 59 } 60 } 61 62 int main() 63 { 64 int i = 0; 65 int num = 3; 66 //Teacher Array[3]; //在stack分配內存 67 68 Teacher *pArray = NULL; 69 pArray = createTeacher(num); 70 71 for (i = 0; i < num; i++) 72 { 73 printf("\nplease enter age:"); 74 scanf("%d", &pArray[i].age); 75 } 76 printTeacher(pArray, num); 77 sortTeacher(pArray, num); 78 printf("排序後:\n"); 79 printTeacher(pArray, num); 80 /* 81 printTeacher(Array, num); 82 sortTeacher(Array, num); 83 printf("排序後:\n"); 84 printTeacher(Array, num);*/ 85 FreeTeacher(pArray); 86 system("pause"); 87 return 0; 88 }