我需要创建一个程序,排序命令行字符串。(代码下的示例输出)
这是我目前掌握的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int stringcomp (const void * x, const void * y);
int main(int argc, char *argv[]){
int i,j;
int k = 1;
char strings[argc-1][20];
strcpy(strings[0], argv[1]);
for(i=2; i< argc-1; i++){
strcat(strings[k],argv[i]);
k++;
}
qsort(strings, argc, 20, stringcomp);
for(j=0 ; j < argc-1; j++){
printf("%s ", strings[j]);
}
return 0;
}
int stringcomp (const void *x, const void *y) {
return (*(char*)x -*(char*)y);
}
这就是我在命令行中键入的内容:
/为了你好黑暗我的老朋友
这就是我应该得到的:
黑暗之友你好我的老朋友
但这就是我一直得到的:
?黑暗?老]@我的
我做错什么了?
最佳答案
从注释开始,为了比较字符串并对字符串数组排序,需要处理两级间接寻址。因此,您的stringcomp
函数需要看起来像:
int stringcomp (const void *x, const void *y) {
return strcmp (*(char * const *)x, *(char * const *)y);
}
除此之外,与其复制字符串,不如对指针数组进行排序,以便按正确的顺序对参数进行排序?你所需要的就是这样:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int stringcomp (const void * x, const void * y);
int main (int argc, char **argv) {
char *strings[argc-1]; /* declare an array of pointers */
int i;
/* assign each argument to a pointer */
for (i = 1; i < argc; i++)
strings[i-1] = argv[i];
/* sort the array of pointers alphabetically with qsort */
qsort (strings, argc - 1, sizeof *strings, stringcomp);
/* output the results */
for (i = 0; i < argc-1; i++)
printf("%s ", strings[i]);
putchar ('\n');
return 0;
}
int stringcomp (const void *x, const void *y) {
return strcmp (*(char * const *)x, *(char * const *)y);
}
示例使用/输出
$ ./bin/sort_argv my dog has fleas
dog fleas has my
再看一遍,如果有其他问题请告诉我。
关于c - 在C中对命令行参数进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36829864/