使用q排序的分割故障
segmentation fault using q sort?
我正在尝试使用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风格函数常见的大多数陷阱。
相关文章:
- 分割故障C++矩阵
- C ,二进制树的高度,而不是检查我的子树是否为空,而是在检查我的子树是否是叶子节点.抛出分割故障
- 我正在为此代码分割故障
- 在执行strcpy时获取分割故障错误
- 空隙指针分割故障
- Xcode会产生分割故障,而不是例外
- OPENCV C 中的分割故障误差
- 分割故障:核心倾倒C 矢量对字符串:
- C 2D数组导致分割故障(核心倾倒)
- 分割故障/错误读数变量-C 列表
- DLSYM导致分割故障
- 使用C 中的操作员删除的分割故障
- 使用Linux X64下的Libmozjs-52(SpidermonKey)进行分割故障
- 使用长变量时分割故障(11)错误
- C - 返回字符串时的分割故障
- 创建VertexArray时的分割故障
- 向量分割故障的向量
- 从std :: fileSystem ::路径对象的类中退出时的分割故障
- C 矢量分割故障
- 基于向量的数据格式的分割故障误差