// ptrsort.c -- 从键盘输入一系列字符串 // 将其按升序或降序排列 // 然后,把排序后的字符串显示在屏幕上 #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXLINES 25 int get_lines(char *lines[]); void sort(char *p[], int n, int sort_type); void print_strings(char *p[], int n); int alpha(char *p1, char *p2); int reverse(char *p1, char *p2); char *lines[MAXLINES]; int main(void){ int number_of_lines, sort_type; //从键盘读入多行字符串 number_of_lines = get_lines(lines); if(number_of_lines < 0){ puts("Memory allocation error"); exit(-1); } puts("Enter 0 for reverse order sort, 1 for alphabetical: "); scanf("%d", &sort_type); sort(lines, number_of_lines, sort_type); printf("\n"); print_strings(lines, number_of_lines); return 0; } int get_lines(char *lines[]){ int n = 0; char buffer[80]; // 临时储存每一行字符串 puts("Enter one lines at time; enter a blank when done."); while(n < MAXLINES && gets(buffer) != 0 && buffer[0] != ‘\0‘){ if((lines[n] = (char *)malloc(strlen(buffer) + 1)) == NULL) return -1; strcpy(lines[n++], buffer); } return n; } // get_lines结束 void sort(char *p[], int n, int sort_type){ int a, b; char *x; //函数指针 int (*compare)(char *s1, char *s2); // 根据sort_type参数的值,让指针指向相应的比较函数 compare = (sort_type) ? reverse : alpha; // if(0 == sort_type){ // compare = reverse; // } // if(1 == sort_type){ // compare = alpha; // } for(a = 1; a < n; a++){ for(b = 0; b < n-1; b++){ if(compare(p[b], p[b+1]) > 0){ x = p[b]; p[b] = p[b+1]; p[b+1] = x; } } } } // sort结束 void print_strings(char *p[], int n){ int count; for(count = 0; count < n; count++){ printf("%s\n", p[count]); } } int alpha(char *p1, char *p2){ // 按字母顺序比较 return (strcmp(p2, p1)); } int reverse(char *p1, char *p2){ //按反向字母比较 return (strcmp(p1, p2)); }
原文:http://my.oschina.net/u/241930/blog/523819