C 字符数组打印比我分配的少1个字符
我正在尝试创建一个字符数为X的字符数组 我需要第一个X-1字符是空格,第X个字符是C 字符数组打印比我分配的少1个字符,c,arrays,string,for-loop,C,Arrays,String,For Loop,我正在尝试创建一个字符数为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 '*'
*
我写了以下内容:
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
}
为什么空格只增长到4个而不是5个字符?
不应该使用空格[4]='*';有人打过电话吗
将整个字符串设置为“*”后,我运行第二个for循环:
for(i = 0; i < X-1; i++) {
spaces[i] = ' ';
}
4个空格,当我需要4个空格,后跟一个
*
时,您缺少字符串终止字符\0
,如果要使用printf(“%s”,…)
将数组打印为字符串,则需要该字符。
因此,使数组比要打印的项目大一个项目,并使用0
对其进行初始化,这样您写入数组的所有内容最终都将是有效字符串。否则会产生未定义的行为:
int main (void)
{
#define X 5
int i = 0;
char spaces[X+1] = { 0 };
for(i = 0; i < X; i++) {
spaces[i] = '*';
printf("spaces = '%s'\n", spaces);
}
}
int main(无效)
{
#定义x5
int i=0;
字符空间[X+1]={0};
对于(i=0;i
将第一个X-1字符设置为空格,第X个字符设置为空格。
这将始终具有最后一个字符a“”
(i=0;i{
空格[i]='';
空间[i+1]='*';
printf(“空格=“%s”\n”,空格);
}
最后一个字符是空终止符
\0
。事实上,您可以使用Xth
元素存储另一个字符,但会将垃圾输出附加到输出中。\n您需要分配更多空间;你没有空终止符。您可以使用char空格[X+1]简洁地完成这项工作;sprintf(空格,“%*c”,X,“*”)代码>。这将用空格填充(右对齐)*
,并使用X-1
空格。这不会以null结尾字符串。
spaces = ' ';
int main (void)
{
#define X 5
int i = 0;
char spaces[X+1] = { 0 };
for(i = 0; i < X; i++) {
spaces[i] = '*';
printf("spaces = '%s'\n", spaces);
}
}
for(i = 0; i < X-1; i++) {
spaces[i] = ' ';
spaces[i+1] = '*';
printf("spaces = '%s'\n", spaces);
}