【发布时间】:2011-09-11 23:10:27
【问题描述】:
我需要对一个字符数组进行排序,以便对其进行迭代并打印出唯一的数据点及其计数。这个数组保存在一个链表节点中,我想使用qsort 来执行此操作。不幸的是,我在该特定行遇到了段错误。
void printArray(Node_ptr node){
int count=0; //character count
char *temp= node->attributes; //duplicate attribute array
char cur; //current char
char *outputCat= emalloc(150); //concatenate counts to a single string
outputCat= "Attribute %d counts are: ";
qsort(&temp, lineCount, sizeof(char), compare); //sort the array
... more code
}
我抄袭了man qsort页面上的比较方法
int compare(const void *a, const void *b){
return strcmp(*(char * const *) a, *(char * const *) b);
}
在 DDD 中,qsort 行是触发 segfault 的行。本来以为是参数不准确,所以放了一些调试printf语句。 printf("%s", temp) 打印出 1000 个字符,这正是行数应该是什么。每个字符都是 1 个字节,所以这里不需要sizeof(char)。
该行来自 ddd 的错误报告是
Program received signal SIGSEGV, Segmentation fault.
0xb7f8c498 in ?? () from /lib/libc.so.6
这是 qsort 的错,还是我的代码有其他问题?
【问题讨论】:
-
outputCat在该代码中扮演什么角色?您正在分配一个新分配的缓冲区,然后将其分配给一个常量字符串(这会泄漏缓冲区,顺便说一句),然后什么都不做。 -
您的
compare函数不正确,正如@wildplasser 指出的那样,但修复需要完全放弃strcmp,它比较字符串,而不是字符。要正确实现它,只需return *(const char *)a - *(const char *)b;。 -
@Marcelo Cantos,outputCat 用于从数组数据构建输出字符串。这就是为什么
qsort功能如此重要的原因。这里没有列出整个函数,因为后面的所有代码都依赖于排序的结果。 -
啊。在这种情况下,您应该
strcpy(outputCat, "Attribute...");。 -
outputCat= "Attribute %d counts are: ";行并没有按照您的想法执行。 Marcello Cantos 是正确的。
标签: c segmentation-fault qsort