Last active
February 7, 2022 00:59
-
-
Save deltheil/5000725 to your computer and use it in GitHub Desktop.
qsort and bsearch over an array of pointers
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
#include <stdio.h> | |
#include <stdlib.h> | |
struct foo { | |
int count; | |
const char *misc; | |
}; | |
typedef struct foo * pfoo; | |
struct foo *foo_new(int c, const char *m); | |
int foo_cmp(const void *a, const void *b); | |
int main() { | |
/* Let's suppose we allocate a dynamic array with a given size */ | |
void **ary = malloc(3*sizeof(void *)); | |
ary[0] = foo_new(4, "mac"); | |
ary[1] = foo_new(1, "linux"); | |
ary[2] = foo_new(9, "windows"); | |
/* Sort by increasing `count`-s */ | |
qsort(ary, 3, sizeof(void *), foo_cmp); | |
/* Now let's retrieve item by count (= search key) */ | |
struct foo f1 = {.count = 4}; | |
struct foo f2 = {.count = 7}; | |
/* bsearch key (1st param) must be of *same* type than array elements! */ | |
struct foo *pf1 = &f1; | |
struct foo **res1 = bsearch(&pf1, ary, 3, sizeof(void *), foo_cmp); | |
printf("search #1 (key = %d) -> %s\n", f1.count, res1 ? "found": "not found"); | |
struct foo *pf2 = &f2; | |
struct foo **res2 = bsearch(&pf2, ary, 3, sizeof(void *), foo_cmp); | |
printf("search #2 (key = %d) -> %s\n", f2.count, res2 ? "found": "not found"); | |
free(ary[0]); | |
free(ary[1]); | |
free(ary[2]); | |
free(ary); | |
return 0; | |
} | |
struct foo *foo_new(int c, const char *m) { | |
struct foo *f = malloc(sizeof(*f)); | |
f->count = c; | |
f->misc = m; | |
return f; | |
} | |
int foo_cmp(const void *a, const void *b) { | |
const pfoo *A = a; | |
const pfoo *B = b; | |
return ( (*A)->count - (*B)->count ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for documenting this!