Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1399422
  • 博文数量: 188
  • 博客积分: 1784
  • 博客等级: 上尉
  • 技术积分: 2772
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-05 22:20
个人简介

发上等愿,结中等缘,享下等福;择高处立,就平处坐,向宽处行。

文章分类

全部博文(188)

文章存档

2020年(12)

2019年(11)

2018年(4)

2017年(3)

2016年(11)

2015年(22)

2014年(19)

2013年(25)

2012年(32)

2011年(49)

分类: LINUX

2011-05-06 23:52:42

#include
#ifndef GENERICS_H
#define GENERICS_H

typedef int (*cmp_t)(void *, void *);
extern void *max(void *data[], int num, cmp_t cmp);

#endif

void *max(void *data[], int num, cmp_t cmp)
{
     int i;
     void *temp = data[0];
     for(i=1; i       if(cmp(temp, data[i])<0)
           temp = data[i];
     }
     return temp;
}
typedef struct {
     const char *name;
     int score;
} student_t;

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)
{
     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 gets the highest score %d\n", pmax->name, pmax->score);

     return 0;
}
阅读(1031) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

5262944122011-05-06 23:56:39

主函数main中
student_t list[4] = {{"Tom", 68}, {"Jerry", 72},
               {"Moby", 60}, {"Kirby", 89}};
调用typedef struct {
     const char *name;
     int score;
} student_t;函数

student_t *pmax = max((void **)plist, 4, cmp_student)调用void *max(void *data[], int num, cmp_t cmp)函数
而void *max(void *data[], int