Skip to content

Instantly share code, notes, and snippets.

@frankie-yanfeng
Created January 10, 2020 01:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankie-yanfeng/23d936ada5e8028717a0b7feda94d554 to your computer and use it in GitHub Desktop.
Save frankie-yanfeng/23d936ada5e8028717a0b7feda94d554 to your computer and use it in GitHub Desktop.
generic example
/* 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;
}
/* 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
/* main.c */
#include <stdio.h>
#include "generics.h"
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment