问题描述
我正在尝试按字母顺序对 argv 的元素进行排序.
I am trying to alphabetically sort the elements of argv.
以下代码行给我带来了问题:
The following line of code is giving me problems:
qsort(argv[optind], argc - optind, sizeof(argv[optind]), sort);
具体来说,最后一个参数给我带来了麻烦,比较函数,下面给出:
Specifically, the last argument is giving me trouble, the comparison function, which is given below:
int
sort(const void *a, const void * b)
{
return(strcmp( (char*)a, (char*)b ));
}
目前,它编译得很好,但是当我运行它时,我最终遇到了分段错误.
At the moment, it compiles fine, but I end up getting a segmentation fault when I run it.
推荐答案
qsort(3)
的手册页包含一个示例,它完全符合您的要求.它还解释了原因:
The man page for qsort(3)
contains one example, which does exactly what you want. It also explains why:
http://linux.die.net/man/3/qsort
总结:您在 qsort()
第一个参数上缺少一级引用,并且在 sort()
函数内部缺少一级取消引用.
Summary: You are missing one level of referencing on the qsort()
first argument, and missing one level of dereferencing inside the sort()
function.
这篇关于如何在 C 中对 argv 的元素进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!