結構體做函式
阿新 • • 發佈:2019-02-01
#include "stdio.h" #include <stdlib.h> #include <string.h> //定義結構體型別 typedef struct T2 { char *name; int age; int score; } T2; //列印 void printfage(T2 *Array,int num) { int i = 0; for(i=0;i<num;i++) { printf("Array[%d] age is %d.\n",i,Array[i].age); } } //排序 void sortage(T2 *Array,int num) { int i = 0 , j = 0; for(i=0;i<num;i++) { for(j=i;j<num;j++) { if(Array[i].age<Array[j].age) { int temp = Array[i].age; Array[i].age = Array[j].age; Array[j].age = temp; } } } } //建立空間 T2* creat(int num) { T2* temp =NULL; int i = 0; temp = (T2*)malloc(sizeof(T2) * num); for(i=0;i<num;i++) { printf("Please input Array[%d] age:",i); scanf("%d",&(temp[i].age)); } return temp; } //釋放空間 void freecreat(T2* p) { if(p != NULL) { free(p); } } void main() { T2* ptemp = NULL; int num = 3; int i=0; ptemp = creat(num); printfage(ptemp,num); sortage(ptemp,num); printfage(ptemp,num); freecreat(ptemp); system("pause"); }