C 从argv排序值

C 从argv排序值,c,sorting,C,Sorting,我在argv中丢失了一些字符串,我想对其进行排序。我正在用strcmp和strcpy进行分类 如何将常量字符**转换为可在排序函数中使用的字符数组 void sort(const char** sl, int n) { char s[n][20], t[20]; int i, j; for (i = 1; i < n; i++) { for (j = 1; j < n; j++) { if (strcmp(s[j - 1], s[j

我在argv中丢失了一些字符串,我想对其进行排序。我正在用strcmp和strcpy进行分类

如何将常量字符**转换为可在排序函数中使用的字符数组

void sort(const char** sl, int n) {

   char s[n][20], t[20];
   int i, j;

   for (i = 1; i < n; i++) {
      for (j = 1; j < n; j++) {
         if (strcmp(s[j - 1], s[j]) > 0) {
            strcpy(t, s[j - 1]);
            strcpy(s[j - 1], s[j]);
            strcpy(s[j], t);
         }
      }
   }

   printf("\nStrings in order are : ");
   for (i = 0; i < n; i++)
      printf("\n%s", s[i]);

}

int main(int argc, const char** argv)
{
  sort(argv+1, argc-1);
  printf("Files: %i\n", argc-1);
  return 0;
}
void排序(常量字符**sl,整数n){
字符s[n][20],t[20];
int i,j;
对于(i=1;i0){
strcpy(t,s[j-1]);
strcpy(s[j-1],s[j]);
strcpy(s[j],t);
}
}
}
printf(“\n按顺序排列的字符串为:”);
对于(i=0;i
您可以使用标准
qsort
功能实现您想要的功能

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int string_cmp(const void *a, const void *b)
{
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
}

void print_args(int argc, char** argv) {
    int i = 0;
    for(i = 0; i < argc; ++i) {
        printf("%s\n", argv[i]);
    }
}

int main(int argc, char** argv) {
    printf("original:\n");
    print_args(argc, argv);

    qsort(argv, argc, sizeof(char *), string_cmp);

    printf("sorted:\n");
    print_args(argc, argv);
    return EXIT_SUCCESS;
}
$ ./String-Sort 432 123456 bhello ahello ch
original:
./String-Sort
432
123456
bhello
ahello
ch
sorted:
./String-Sort
123456
432
ahello
bhello
ch
输出:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int string_cmp(const void *a, const void *b)
{
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
}

void print_args(int argc, char** argv) {
    int i = 0;
    for(i = 0; i < argc; ++i) {
        printf("%s\n", argv[i]);
    }
}

int main(int argc, char** argv) {
    printf("original:\n");
    print_args(argc, argv);

    qsort(argv, argc, sizeof(char *), string_cmp);

    printf("sorted:\n");
    print_args(argc, argv);
    return EXIT_SUCCESS;
}
$ ./String-Sort 432 123456 bhello ahello ch
original:
./String-Sort
432
123456
bhello
ahello
ch
sorted:
./String-Sort
123456
432
ahello
bhello
ch
但如果仍然需要自己的函数,只需初始化数组
s
,如下所示

for(i = 0; i < n; ++i) {
    strcpy(s[i], sl[i]);
}
(i=0;i{ strcpy(s[i],sl[i]); }
将其添加到排序循环之前。但是您需要确保每个输入字符串的长度小于20,或者您需要为字符串分配更多内存。

之所以如此,是因为您将
s1
中的字符串与未初始化的数组
s[j]
进行了比较。我还没有进行任何比较,因为我不知道如何从const char**转换为char[]…在
sort
中,您有表达式
strcmp(s[j-1],s[j])
,当您第一次调用函数时,
s[j]
将被取消初始化,从而导致UB。非常感谢,但它不能按我的需要工作,我需要排序的字符串是a.1 a.2 a.3 a.4-a.10,它总是像a.1 a.10 a.2….@Merl这就是strcmp的工作原理,用你的方法你仍然会得到这样的结果。使用
strerscmp
实现正确的数字比较。