获取字符串数组的意外输出
Getting unexpected output for string array
a = 1;
b = 9;
char s[9][5]={"one","two","three","four","five","six","seven","eight","nine"};
for(int i=a;i<=b;i++)
{
if(i<10)
printf("%s\n",s[i-1]);
else
{
if(i%2==1)
printf("odd\n");
else
printf("even\n");
}
}
预计:
one
two
three
four
five
six
seven
eight
nine
得到:
one
two
threefour
four
five
six
seveneightnine
eightnine
nine
不是这个数组的所有元素
char s[9][5]={"one","two","three","four","five","six","seven","eight","nine"};
包含一个字符串。元素的类型是 char[5]
。因此,例如字符串文字 "three"
未完全包含在数组的第三个元素中,因为没有 space 来存储字符串文字和转换说明符的终止零字符 '[=17=]'
%s
旨在输出字符,直到遇到终止零字符 '[=17=]'
。这就是出现
这样的输出的原因
threefour
seveneightnine
eightnine
所以要么你需要增加数组元素的大小,比如
char s[9][6]= { /*...*/ };
或在 printf
的调用中使用以下格式字符串
printf("%.*s\n", 5, s[i-1]);
注意这个if语句
if(i<10)
没有什么意义,因为我总是小于 10。
a = 1;
b = 9;
char s[9][5]={"one","two","three","four","five","six","seven","eight","nine"};
for(int i=a;i<=b;i++)
{
if(i<10)
printf("%s\n",s[i-1]);
else
{
if(i%2==1)
printf("odd\n");
else
printf("even\n");
}
}
预计:
one
two
three
four
five
six
seven
eight
nine
得到:
one
two
threefour
four
five
six
seveneightnine
eightnine
nine
不是这个数组的所有元素
char s[9][5]={"one","two","three","four","five","six","seven","eight","nine"};
包含一个字符串。元素的类型是 char[5]
。因此,例如字符串文字 "three"
未完全包含在数组的第三个元素中,因为没有 space 来存储字符串文字和转换说明符的终止零字符 '[=17=]'
%s
旨在输出字符,直到遇到终止零字符 '[=17=]'
。这就是出现
threefour
seveneightnine
eightnine
所以要么你需要增加数组元素的大小,比如
char s[9][6]= { /*...*/ };
或在 printf
printf("%.*s\n", 5, s[i-1]);
注意这个if语句
if(i<10)
没有什么意义,因为我总是小于 10。