简体   繁体   中英

quick sort problem

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,iCountElement,(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.

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