我需要对一个字符数组进行排序,以便对其进行迭代,并打印出唯一的数据点及其计数。这个数组保存在一个链表节点中,我想使用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页面中抄袭了compare方法
int compare(const void *a, const void *b){
return strcmp(*(char * const *) a, *(char * const *) b);
}在DDD中,qsort行是触发段错误的行。我最初认为这是由于参数中的错误,所以我放入了一些调试printf语句。printf("%s", temp)打印出1000个字符,这正是linecount应该输出的字符。每个字符是1个字节,所以这里不需要sizeof(char)。
在该行上来自ddd错误报告是
Program received signal SIGSEGV, Segmentation fault.
0xb7f8c498 in ?? () from /lib/libc.so.6这是qsort的错误,还是我的代码出了什么问题?
发布于 2011-09-12 07:19:46
这
qsort(&temp, lineCount, sizeof(char), compare);应该是:
qsort(temp, lineCount, sizeof(char), compare);您不需要传递指针的地址!
qsort的第一个参数是一个指针,所以如果你给它传递一个指针,你不需要使用address-of操作符,否则你就是在传递一个指向指针的指针,在本例中这不是你想要的。
发布于 2011-09-12 07:18:33
如果要对字符进行排序,qsort()的第一个参数应该是字符指针,而不是指向字符指针的指针。strcmp()也是如此
另外:请添加struct node的定义。
https://stackoverflow.com/questions/7381905
复制相似问题