简体   繁体   中英

It seems my qsort didn't give correct result why?

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.

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 );
}

qsort passes to compare the address (not value) of each element of the array, ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM