c - 数组中的字符串顺序
问题描述
我有下一个代码,
你猜我希望看到最后一行的输出: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;
}
解决方案
原因是这一行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;
}
推荐阅读
- bash - 从 Bash 中的自定义选项读取参数
- javascript - 如何限制用户在移动设备上触摸 chrome 标题栏和 3 个垂直点
- ios - 使用 AVFoundation 将 AAC 音频和 h.264 视频流混合到 mp4
- install4j - Install4j - 是否可以运行 TSQL 查询?
- ios - 如何为 UINavigationBar 的后退按钮创建阴影?
- android - 如何使用 Android Studio 将数据从 Raspberry pi 发送到 Google Cloud IoT Core?
- java - yml 文件中的属性值未加载到 springboot 项目中的类中
- python - 改变形状并随机排列一个数组
- shell - Shell - 用户列的总和
- emacs - Emacs 25.0.50 中的递归加载