Skip to content

Instantly share code, notes, and snippets.

@ox
Created January 21, 2012 15:11
Show Gist options
  • Save ox/1653029 to your computer and use it in GitHub Desktop.
Save ox/1653029 to your computer and use it in GitHub Desktop.
sorting C structs, an example
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