为什么我的字符串在初始化时会连接起来?
Why are my strings getting concatenated as I initialize them?
我正在尝试练习声明字符串,但没有得到正确的输出。
#include <stdio.h> //Im using vscode and gcc
int main()
{
char k[]= "prac c";
char l[6]= "stop c"; //first initializing as size 6
char m[6]= "nice c";
printf("%s \n%s \n%s",k,l,m);
return 0;
}
output: prac c
stop cprac c
nice cstop cprac c
但是当我将大小从 6 更改为 7 时,这并没有发生。
#include <stdio.h>
int main()
{
char k[]= "prac c";
char l[7]= "stop c"; //changing size to 7
char m[7]= "nice c"; //changing size to 7
printf("%s \n%s \n%s",k,l,m);
return 0;
}
output: prac c
stop c
nice c
"prac c", "stop c", "nice c"
都分别占用 7 个字节,因为字符串文字有终止符 [=11=]
。
字符串"stop c"
实际上是七个个字符长,包括结尾空终止符。这适用于您的所有字符串。
如果你的数组中没有space作为终结符,那么它就不会被添加,并且数组不再是通常所说的字符串。
使用像字符串这样的数组将导致代码超出数组的范围并给你未定义的行为。
我正在尝试练习声明字符串,但没有得到正确的输出。
#include <stdio.h> //Im using vscode and gcc
int main()
{
char k[]= "prac c";
char l[6]= "stop c"; //first initializing as size 6
char m[6]= "nice c";
printf("%s \n%s \n%s",k,l,m);
return 0;
}
output: prac c
stop cprac c
nice cstop cprac c
但是当我将大小从 6 更改为 7 时,这并没有发生。
#include <stdio.h>
int main()
{
char k[]= "prac c";
char l[7]= "stop c"; //changing size to 7
char m[7]= "nice c"; //changing size to 7
printf("%s \n%s \n%s",k,l,m);
return 0;
}
output: prac c
stop c
nice c
"prac c", "stop c", "nice c"
都分别占用 7 个字节,因为字符串文字有终止符 [=11=]
。
字符串"stop c"
实际上是七个个字符长,包括结尾空终止符。这适用于您的所有字符串。
如果你的数组中没有space作为终结符,那么它就不会被添加,并且数组不再是通常所说的字符串。
使用像字符串这样的数组将导致代码超出数组的范围并给你未定义的行为。