如何在 C 中对 argv 的元素进行排序? [英] How do I sort the elements of argv in C?

查看:32
本文介绍了如何在 C 中对 argv 的元素进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按字母顺序对 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 的元素进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆