[英]quick sort problem
I use qsort from C libary and I have datatype 我使用来自C libary的qsort,并且具有数据类型
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. 您的比较函数应通过分别返回负值,零或正值来返回是否认为elem1小于,等于或大于elem2。
Also if you want to sort for example an array of Element_Type
then you would cast the void*
to type Element_Type*
. 同样,如果您想对例如
Element_Type
的数组进行排序,则可以将void*
Element_Type*
转换为Element_Type*
。 If your elements that you are trying to sort are Element_Type*
then you would cast the void* to Element_Type**
. 如果要排序的元素是
Element_Type*
则可以将void * Element_Type**
为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. 如果要排序的项目类型为
Element_Type*
,请确保为每个项目分配内存,然后在调用qsort之前为每个项目初始化内存。
pElement = (Element_type *)malloc(sizeof(Element_type )* iiNewSize);
You should call qsort(pElement, ...), not qsort(*pElement, ...). 您应该调用qsort(pElement,...),而不是qsort(* pElement,...)。 The pElement declaration at the top of your post cannot be accurate.
帖子顶部的pElement声明不正确。
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:
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. 我看不到第一个代码段,因此不会对您的段错误提出建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.