在c中,当我使用%s打印字符数组的内容时,它打印空白,但是当我循环它并打印每个字符时,它工作



只是实现一个简单的排序算法来对字符串进行排序。我试着用printf("%sn")打印出buff字符数组,但它出现空白。但是,数组的内容在那里,我检查了打印出它的每个字符。我遗漏了什么?

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{   
if (argc != 2)
{
printf("usage: ./sortstring string");
exit(1);
}
int size = 1; // 1 to account for ''
for (int i = 0; argv[1][i] != ''; i++)
{
size += 1;
}
char buff[size];
strcpy(buff, argv[1]);
char temp;
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (tolower(buff[i]) > tolower(buff[j]))
{
temp = buff[i];
buff[i] = buff[j];
buff[j] = temp;
}
}
}
// printf("%sn", buff);
for (int i = 0; i < size; i++)
{
printf("%c", buff[i]);
}
return 0;
}

printf中的"%c"改为"%d",查看结果

for (int i = 0; i < size; i++)
{
printf("%d", buff[i]);
}

strcpy用源字符串复制终止空字节。
您用其他字符对终止空字节进行排序。

您的排序函数可能将空字符排序到位置0。

不需要手动计算"argc[1]"中的字符数,只需使用"strlen"函数。所以,不用

int size = 1; // 1 to account for ''
for (int i = 0; argv[1][i] != ''; i++)
{
size += 1;
}

你可以用

int size = strlen(argv[1]);

致意。

问题是您正在用1初始化size。我知道你这么做是因为你还需要一个字符到,但在那之后,要么你需要循环size - 1,要么你可以在for循环之前减少size的值。

你可以做的另一件事是:用0初始化size,并在创建数组时使用size + 1