开发者

quick sort problem

开发者 https://www.devze.com 2023-01-02 22:53 出处:网络
I use qsort from C libary and I have datatype Element_type **pElement and Element_type is struct typedef element_type {int ,char ....}

I use qsort from C libary and I have datatype

Element_type **pElement and Element_type is struct typedef element_type {int ,char ....} 

example, and i call quicksor function with

qsort(*pElement,iCountElemen开发者_如何学运维t,(size_t)sizeof(Element_type),compare);

and callback function

static int compare(const void *p1, const void *p2) {
    Element_type  *a1 = (Element_type  *)p1;
    Element_type *a2 =  (Element_type   *)p2;
    return ( (a2)->iServiceId < (a1)->iServiceId );
}

but I always get segmentation fault. Why?


Your compare function should return whether elem1 is considered less than, equal to, or greater than elem2 by returning, respectively, a negative value, zero or a positive value.

Also if you want to sort for example an array of Element_Type then you would cast the void* to type Element_Type*. If your elements that you are trying to sort are Element_Type* then you would cast the void* to Element_Type**.

If the items you are trying to sort are of type Element_Type* the make sure you are allocating memory for each of those items and then initialized for each item before calling qsort.


   pElement = (Element_type *)malloc(sizeof(Element_type )* iiNewSize);

You should call qsort(pElement, ...), not qsort(*pElement, ...). The pElement declaration at the top of your post cannot be accurate.


static int compare(const void *p1, const void *p2) {
    Element_type  *a1 = *(Element_type  *)p1;
    Element_type *a2 =  *(Element_type   *)p2;

    if( (a1)->iServiceId < (a2)->iServiceId )
    {
        return -1; // this means that a1 < a2 in your criteria
    }

    if( (a1)->iServiceId == (a2)->iServiceId )
    {
        return 0; // this means that a1 == a2 in your criteria
    }

    return 1; // this means that a1 > a2 in your criteria
}

Call qsort like this:

qsort(pElement,iCountElement,(size_t)sizeof(Element_type),compare);

LATER EDIT: give us a piece of code so we can see more problems if that's the case


This is the easiest way to correct your compare function:

 static int compare(const void *p1, const void *p2) {
    Element_type  *a1 = (Element_type  *)p1;
    Element_type *a2 =  (Element_type   *)p2;
-   return ((a2)->iServiceId < (a1)->iServiceId );
+   return (a1->iServiceId) - (a2->iServiceId);
 }

I can't read the first code segment, so I won't make suggestions on your segfault.

0

精彩评论

暂无评论...
验证码 换一张
取 消