首页 > 解决方案 > 数组中的字符串顺序

问题描述

我有下一个代码,
你猜我希望看到最后一行的输出:a , b ,c ,d但实际输出是:

a d (null) (null)  
a c d (null)  
a b c d  
a b b c

最后一行,为什么我看到它?

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

int main ()
{
    char *str_tmp[4] = {"d", "a", "c", "b"};
    char **str = calloc(4, sizeof(char *));

    str[0] = str_tmp[0];

    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < i; j++)
        {
            if (strcmp(str_tmp[i], str[j]) < 0)
            {
                for (int k = i; k > j; k--)
                {
                    str[k] = str[k-1];
                }

                str[j] = str_tmp[i];

                for (int n = 0; n < 4; n++)
                {
                    printf("%s ", str[n]);
                }
                printf("\n");
            }
        }
    }

    return 0;
}

标签: csortingfor-loopc-stringsinsertion-sort

解决方案


原因是这一行str[j] = str_tmp[i];中仍然存在的最少元素是b,您需要交换它

请使用简单的方法进行交换

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

int main ()
{
    char *str_tmp[4] = {"d", "a", "c", "b"};
    char *temp = "";

    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < i; j++)
        {
            if (strcmp(str_tmp[i], str_tmp[j]) < 0)
            {
                temp = str_tmp[i];
                str_tmp[i] = str_tmp[j];
                str_tmp[j] = temp;
            }
        }
    }

    for (int n = 0; n < 4; n++)
    {
         printf("%s ", str_tmp[n]);
    }

    return 0;
}

推荐阅读