Created
January 21, 2012 15:11
-
-
Save ox/1653029 to your computer and use it in GitHub Desktop.
sorting C structs, an example
This file contains hidden or 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
typedef struct stump { | |
char * name; | |
int data; | |
} stump; | |
typedef struct container { | |
stump ** node_array; | |
} container; | |
int compare_stumps(const void *a, const void *b) { | |
stump *ia = (stump *)a; | |
stump *ib = (stump *)b; | |
return (int)(ia->data - ib->data); | |
} | |
int main(int argc, char **argv) { | |
container *c = malloc(sizeof(container *)); | |
c->node_array = calloc(2, sizeof(stump *)); | |
stump *one = malloc(sizeof(stump *)); | |
stump *two = malloc(sizeof(stump *)); | |
one->name = "a"; | |
one->data = 1; | |
two->name = "b"; | |
two->data = 2; | |
c->node_array[0] = two; | |
c->node_array[1] = one; | |
qsort(c->node_array, 2, sizeof(stump *), compare_stumps); | |
printf("%i, %i", c->node_array[0]->data, c->node_array[1]->data); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment