Hi, I have a qsort problem I just can't solve.
I've got an array of pointers to a structure called struct mys. The structure has an int value called id. I want to use qsort to sort this array of pointers to structure in ascending order by the id value in each of the structures referenced. Hope I'm making sense. Here is the code I've tried:
#include <stdio.h>
#include <stdlib.h>
struct mys {
int id;
int size;
};
int indirectstructsortbyid(const void *i1, const void *i2) {
struct mys *a = (struct mys *)i1;
struct mys *b = (struct mys *)i2;
return (a->id - b->id);
}
void sort_indirect_structs() {
struct mys master[] = { {11, 11}, {33, 33}, {55, 55}, {77, 77}, {99, 99},
{22, 22}, {44, 44}, {66, 66}, {88, 88}
};
struct mys **mboo;
int count = sizeof(master) / sizeof(struct mys);
mboo = malloc (sizeof(struct mys*) * count);
int i;
for (i = 0; i < count; i++) {
*(mboo+i) = &master[i];
}
printf("\nbefore qsort\n");
for (i = 0; i < count; i++) {
printf("%d: id = %d, size = %d\n", (i+1), (**(mboo+i)).id, (**(mboo+i)).size);
}
qsort(mboo, count, sizeof(struct mys*), indirectstructsortbyid);
printf("\nafter qsort\n");
for (i = 0; i < count; i++) {
printf("%d: id = %d, size = %d\n", (i+1), (**(mboo+i)).id, (**(mboo+i)).size);
}
free(mboo);
}
int main()
{
sort_indirect_structs();
return 0;
}
Thanks for your help...