Created
January 10, 2020 01:56
-
-
Save frankie-yanfeng/23d936ada5e8028717a0b7feda94d554 to your computer and use it in GitHub Desktop.
generic example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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