c - 使用函数通过 strcmp 对 argv 值进行排序

标签 c

我想用我自己的函数来完成它(我知道 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/

相关文章:

将 char* 的一部分转换为 int

c++ - 如何使用 C++ 使用 VLC 播放器运行视频文件

c - strcpy 时出现段错误

c - 获取段错误而不是打印结构值

c - 将字符串中的十六进制值读入十进制长

C,列表的最后一个元素指向空

c - 函数 strlen 中的警告 - 在 C 中

c - mapPut 有什么问题?我找不到问题

c - 指针 MISRA 违规的算术

c - 用于读取输入的动态缓冲区大小