max 函数可以在任意一组对象中找出最大值,实现者并不知道怎样去比较两个对象的大小,调用者需要提供一个做比较操作的回调函数。
// generics.h
#ifndef GENERICS_H
#define GENERICS_H
typedef int (*cmp_t)(void *, void *);
extern void *max(void *data[], int num, cmp_t cmp);
#endif
// generics.c
#include "generics.h"
void *max(void *data[], int num, cmp_t cmp) {
int i;
void *temp = data[0];
for(i = 1; i < num; i ++) {
if(cmp(temp, data[i]) < 0) {
temp = data[i];
}
}
return temp;
}
// genericsMain.c
#include <stdio.h>
#include "generics.h"
typedef struct {
const char *name;
int score;
} student_t;
int comple_int(void *a, void *b) {
if((int *)a > (int *)b)
return 1;
else if((int *)a == (int *)b)
return 0;
else
return -1;
}
int cmp_student(void *a, void *b) {
if(((student_t *)a)->score > ((student_t *)b)->score )
return 1;
else if (((student_t *)a)->score == ((student_t *)b)->score )
return 0;
else
return -1;
}
int main(void) {
int data[5] = {1, 3, 6, 4, 8};
int *pdata[5] = {&data[0], &data[1], &data[2], &data[3], &data[4]};
int *presult = max((void **)pdata, 5, comple_int);
printf("result %d\n", *presult);
student_t list[4] = {{"Tom", 68}, {"Jerry", 72}, {"Moby", 60}, {"Kirby", 89}};
student_t *plist[4] = {&list[0], &list[1], &list[2], &list[3]};
student_t *pmax = max((void **)plist, 4, cmp_student);
printf("%s %d\n", pmax->name, pmax->score);
return 0;
}