怎样的argv C中的元素进行排序? [英] How do I sort the elements of argv in C?

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

问题描述

我想要的argv按字母顺序排序的元素。

I am trying to alphabetically sort the elements of argv.

code的下面一行是给我的问题:

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()第一个参数,缺少内提领一个级别一个级别的排序() 功能。

Summary: You are missing one level of referencing on the qsort() first argument, and missing one level of dereferencing inside the sort() function.

这篇关于怎样的argv C中的元素进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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