There are lots of questions on stackoverflow regarding how to sort an array of structure pointers. I looked through them all, to no avail. I want to sort an array of pointers to an array of structures. I first allocate storage for the pointer array, then for the structures themselves. All that seems fine, but I can't get them sorted. I'm sure the problem is in the compare function. I've copied a few of them from stackoverflow, and they are listed below. But none of them work...
typedef struct s_stream{
int amc;
char *name;
} dataStream;
void abc(void)
{
int count = 100;
dataStream *_UniqueStreamBuild = calloc(count, sizeof(dataStream ));
dataStream **UniqueStreamBuild = calloc(count, sizeof(dataStream *));
for ( int i = 0; i < count; ++i) UniqueStreamBuild[i] = _UniqueStreamBuild + i;
//**Edit: ******** **
// here I call a cascade of functions that assign values to amc; those
// functions are correct: they produce an unsorted array of amc values;
// the output I am getting is an array of structures seemingly in random order.
qsort(UniqueStreamBuild, count, sizeof(dataStream *), compare);
}
int compare (const void * a, const void * b)
{
const dataStream *x = a;
const dataStream *y = b;
if (x->amc > x->amc)
return(1);
if (x->amc < x->amc)
return(-1);
return(0);
}
int compare( const void *a, const void *b )
{
dataStream *m1 = *(dataStream **)a;
dataStream *m2 = *(dataStream **)b;
if (m1->amc > m2->amc)
return(1);
if (m1->amc < m2->amc)
return(-1);
return(0);
}