Reputation: 752
this is my compare function:
int compare (const void * a, const void * b)
{
ptnode * ia = (ptnode*)a;
ptnode * ib = (ptnode*)b;
return (int)(100.f*ia->x - 100.f*ib->x );
}
and I called qsort as:
qsort(sortbase,index,sizeof(ptnode),compare);
sortbase is an array of my struct ptnode, defined as:
typedef struct node
{
struct node *pre1;
struct node *pre2;
struct node *pre;
double x;
double y;
double maxlength;
} ptnode;
sortbase is like this:
struct node * sortbase[1000];
I want to sort them by their x value,but before and after qsort, there's nothing changed,
whY? thanks in advance.
Upvotes: 1
Views: 155
Reputation: 57470
qsort
passes to compare
the address (not value) of each element of the array, i.e., it passes a pointer to a pointer to a ptnode
. You need to change the first line of compare
to:
ptnode * ia = *(ptnode**)a;
and likewise for the second line.
Upvotes: 3
Reputation: 229058
The compare function receives a pointer to the 2 elements you need to compare. Since your elements are pointers, the compare function needs to handle pointer to pointers.
int compare (const void * a, const void * b)
{
ptnode * ia = *(ptnode**)a;
ptnode * ib = *(ptnode**)b;
return (int)(100.f*ia->x - 100.f*ib->x );
}
Upvotes: 5