我正在尝试使用qsort对字符的指针数组进行排序,并且在编译时不断出现分段错误。我将发布我的qsort调用和比较函数的代码,如果有任何帮助,我们将不胜感激。
//count declaration
size_t count = (sizeof (strPtrsQsort)/sizeof (*strPtrsQsort));
//function call
qsort ((char *)ptr, size, sizeof(char), compare);
//compare function
int compare (const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp (*ia, *ib);
}
根据qsort
调用判断,您正在对char
元素的数组进行排序:基指针类型作为char *
值传递给qsort
,元素大小为sizeof(char)
。但是,您的比较函数是为char
的指针数组编写的。这是完全不正确和不一致的。这就是造成这次事故的原因。
在附带的文本中,您声明您正在"尝试对字符的指针数组进行排序"。在这种情况下,为什么要将元素大小指定为sizeof(char)
而不是sizeof (char *)
?
请注意,即使需要使用C样式的原始数组,您仍然可以使用C++STL算法,因为指针实际上是RandomAccessIterator。例如,这是有效的:
#include <algorithm>
#include <iostream>
#include <cstring>
static
bool compare(const char *a, const char *b)
{
return std::strcmp(a, b) < 0;
}
int main()
{
const char *stringarray[] = {
"zyxulsusd",
"abcdef",
"asdf"
};
std::sort(stringarray, stringarray + 3, compare);
// -----------^
// Just like a normal iterator the end iterator points
// to an imaginary element behind the data.
for(int i = 0; i < 3; i++) {
std::cout << stringarray[i] << std::endl;
}
return 0;
}
这种方法的主要优点是类型安全,因此避免了像qsort
这样的C风格函数常见的大多数陷阱。