使用 qsort 出现段错误
我需要对字符数组进行排序,以便对其进行迭代并打印出唯一的数据点及其计数。该数组保存在链表节点内,我想使用 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 行是触发段错误的行。本来以为是参数不准确,所以加了一些调试printf语句。 printf("%s", temp)
打印出 1000 个字符,这正是行数应有的值。每个字符都是 1 个字节,因此这里不需要 sizeof(char)
。
该行上 ddd 的错误报告是“
Program received signal SIGSEGV, Segmentation fault.
0xb7f8c498 in ?? () from /lib/libc.so.6
这是 qsort 的错误,还是我的代码有其他问题?”
I need to sort an array of characters in order to iterate over it and print out the unique data points and their count. This array is held inside a linked list node, and I want to use qsort
to do this. Unfortunately, I'm getting a segfault right at that particular line.
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
}
I cribbed the compare method from the man qsort
page
int compare(const void *a, const void *b){
return strcmp(*(char * const *) a, *(char * const *) b);
}
In DDD, the qsort line is the one that triggers the segfault. I originally thought it was due to inaccuracies in the parameters, so I put in some debugging printf statements. printf("%s", temp)
prints out 1000 characters, which is exactly what linecount should be. Chars are 1 byte each, so no need for sizeof(char)
here.
The error report from ddd on that line is
Program received signal SIGSEGV, Segmentation fault.
0xb7f8c498 in ?? () from /lib/libc.so.6
Is this qsort's fault, or something else with my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这
应该是:
您不需要传递指针的地址!
qsort
的第一个参数是一个指针,因此如果你向它传递一个指针,则不需要使用地址运算符,否则你将传递一个指向指针的指针,这不是在这种情况下你想要什么。This
Should be:
You do not need to pass the address of a pointer!
qsort
's first argument is a pointer, so if you pass it a pointer, you do not need to use the address-of operator, else you're passing a pointer to a pointer, which is not what you want in this case.如果要对字符进行排序,qsort() 的第一个参数应该是字符指针,而不是指向字符指针的指针。 strcmp() 也是如此
另外:请添加结构节点的定义。
If you want to sort characters, the first argument to qsort() should be a character pointer, not a pointer to a character pointer. The same for the strcmp()
Also: please add the definition for struct node.