【发布时间】:2017-10-21 20:20:41
【问题描述】:
我正在尝试创建一个字符数为 X 的字符数组。
我需要前 X-1 个字符是空格,我需要第 X 个字符是 *。
我写了以下内容:
int i = 0;
int X = 5;
char spaces[X]; //In this case X is 5 so the array should have indexes 0 - 4
for(i = 0; i < X; i++) {
spaces[i] = '*'; //I start by setting all 5 char's equal to '*'
printf("spaces = '%s'\n", spaces); //This was to make sure it ran the correct # of times
}
该段的输出如下,'gh'每次都不一样:
spaces = '*gh'
spaces = '**h'
spaces = '***'
spaces = '****'
spaces = '****'
为什么空格只增长到 4 个字符而不是 5 个字符? 不应该空格[4] = '*';被叫了吗?
在将整个字符串设置为 '*' 之后,我运行了第二个 for 循环:
for(i = 0; i < X-1; i++) {
spaces[i] = ' ';
}
然后应该将除第 X 个字符之外的所有字符都设置为 ' ',但由于字符串的行为就像它只有 X-1 个字符一样长,所以整个东西都设置为空格,结果如下所示
spaces = ' ';
4 个空格,当我需要 4 个空格后跟 *。
【问题讨论】:
-
最后一个字符是
Null terminator\0。 -
事实上,您可以使用
Xth元素来存储另一个字符,但您的输出会附加垃圾输出。\ -
点赞this
-
您需要分配更多空间;你没有空终止符。您可以使用
char spaces[X+1]; sprintf(spaces, "%*c", X, '*');简洁地完成这项工作。这将空白填充(右对齐)*和X-1空格。