I am having trouble sorting a 2D dynamic struct array.
I have a struct:
typedef struct abc
{
int total;
} abc;
And a dynamic 2D array:
list = (abc**)malloc(listSize * sizeof(abc*));
for (int i = 0; i < listSize; i++)
{
list[i] = (abc*)malloc(listSize2* sizeof(abc));
}
I want to use a sorting algorithm:
qsort(list, listSize, sizeof list[0], cmp);
and the compare function for the qsort:
int cmp(const void *l, const void *r)
{
const abc *a = *(const abc **)l;
const abc *b = *(const abc **)r;
return a[0].total > b[0].total;
}
But the problem is that although I think it works for a small list (like about 5 ints), it fails to sort properly if the list is a bit bigger. What should I do to the cmp() function so it works properly?
By the way, I only need to sort list[x][0]
since I will be adding more elements later.
(I'm basing my sorting code from another Stackoverflow post)