我想用我自己的函数来完成它(我知道 qsort 可能是一个更好的选择)。 这是我所做的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void order(int count, char** strings);
int main(int argc, char** argv)
{
int i = 0;
for (i = 1; i < argc; i++)
{
printf("%s, ", argv[i]);
}
printf("\nAfter: \n");
order(argc, argv);
for (i = 1; i < argc; i++)
{
printf("%s, ", argv[i]);
}
getchar();
return 0;
}
void order(int count, char** strings)
{
char temp[50] = { 0 };
int x = 0, y = 0;
for (x = 1; x < count - 1; x++)
{
for (y = 0; y < count - x - 1; y++)
{
if (strcmp(strings[y], strings[y + 1]) > 1)
{
strcpy(temp, strings[y]);
strcpy(strings[y], strings[y+1]);
strcpy(strings[y+1], temp);
}
}
}
}
它不会改变数组中的任何内容,我将不胜感激任何形式的帮助,谢谢!
最佳答案
您使用的strcmp
结果是错误的。根据其 man
页面,它
return an integer greater than, equal to, or less than 0, if the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2, respectively.
所以这一行是错误的:
if (strcmp(strings[y], strings[y + 1]) > 1)
与 0 进行比较以使其起作用。
关于c - 使用函数通过 strcmp 对 argv 值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36967980/