函数指针的使用(字符串排序)
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #include<time.h> 5 6 //申请内存空间 7 char **apply(int len); 8 9 //返回一个字符串 10 char *assign(); 11 12 //初始化字符串数组 13 void init(char **beg, char **end, char* (*operate)()); 14 15 //打印字符串数组 16 void print(char **arr, int len); 17 18 //升序排序 19 int asc(const void *left, const void *right); 20 //将序排序 21 int desc(const void *left, const void *right); 22 23 int main() 24 { 25 char **str; 26 int num;//字符串个数 27 srand(time(NULL)); 28 num = rand() % 10 + 1; 29 str = apply(num); 30 31 init(str,str+num-1,&assign); 32 printf("排序前: "); 33 print(str,num); 34 35 //运用函数库的快速排序 36 qsort(str,num,sizeof(char*),&asc); 37 38 printf("排序后: "); 39 print(str,num); 40 return 0; 41 } 42 43 char **apply(int len) 44 { 45 char **arr = (char**)calloc(len,sizeof(char*)); 46 return arr; 47 } 48 //返回一个字符串 49 char *assign() 50 { 51 int i; 52 int len = rand() % 10 + 1;//字符串长度 53 char *pstr = (char*)calloc(len,sizeof(char)); 54 55 for(i = 0; i < len; i++) 56 pstr[i] = rand() % 26 + 'a'; 57 pstr[i] = '