使用man qsort查看原型
void qsort(void *base, size_t nmemb, size_t size,
int(*compar)(const void *, const void *));
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/time.h> #define SIZE(__arr) (sizeof(__arr[0])) #define NMEMB(__arr) (sizeof(__arr) / SIZE(__arr)) struct bucket { char a; int b; int c; }; unsigned int seed_get(void) { unsigned int seed = 0; FILE *dev_urandom; struct timeval now; do { dev_urandom = fopen("/dev/urandom", "rb"); } while (dev_urandom == NULL && errno == EINTR); if (dev_urandom) { int r; setvbuf(dev_urandom, NULL, _IONBF, 0); do { errno = 0; r = fread(&seed, sizeof(seed), 1, dev_urandom); } while (errno == EINTR); if (r != 1) { seed = 0; } fclose(dev_urandom); } if (seed == 0) { gettimeofday(&now, NULL); seed = now.tv_usec; } return seed; } /* @return : [0, RAND_MAX] */ int rand_get(void) { unsigned int seed = seed_get(); srand(seed); return rand(); } int cmpar(const void *a, const void *b) { struct bucket *_a = (struct bucket *)a; struct bucket *_b = (struct bucket *)b; return (_a->c - _b->c); } int main(void) { int i; struct bucket arr[10]; for (i = 0; i < NMEMB(arr); i++) { arr[i].c = rand_get() % 1000; printf("%5d\t", arr[i].c); } printf("\n"); qsort(arr, NMEMB(arr), SIZE(arr), cmpar); for (i = 0; i < NMEMB(arr); i++) { printf("%5d\t", arr[i].c); } printf("\n"); return 0; }