C 字符串初始值设定项不包括终止符? [英] C string initializer doesn't include terminator?
问题描述
我对以下 C 代码片段感到有些困惑:
I am a little confused by the following C code snippets:
printf("Peter string is %d bytes\n", sizeof("Peter")); // Peter string is 6 bytes
这告诉我,当 C 编译双引号中的字符串时,它会自动为空终止符添加一个额外的字节.
This tells me that when C compiles a string in double quotes, it will automatically add an extra byte for the null terminator.
printf("Hello '%s'\n", "Peter");
printf
函数知道什么时候停止读取字符串Peter",因为它到达了空终止符,所以......
The printf
function knows when to stop reading the string "Peter" because it reaches the null terminator, so ...
char myString[2][9] = {"123456789", "123456789" };
printf("myString: %s\n", myString[0]);
此处,printf
打印所有 18 个字符,因为没有空终止符(如果不去掉 9,它们将不适合).C 不会在变量定义中添加空终止符吗?
Here, printf
prints all 18 characters because there's no null terminators (and they wouldn't fit without taking out the 9's). Does C not add the null terminator in a variable definition?
推荐答案
你的字符串是 [2][9].那些 [9] 是 ['1', '2', etc... '8', '9'].因为您在第一个数组维度中只给了它 9 个字符的空间,并且因为您使用了所有 9 个字符,所以它没有空间放置 '\0' 字符.重新定义你的字符数组:
Your string is [2][9]. Those [9] are ['1', '2', etc... '8', '9']. Because you only gave it room for 9 chars in the first array dimension, and because you used all 9, it has no room to place a '\0' character. redefine your char array:
char string[2][10] = {"123456789", "123456789"};
它应该可以工作.
这篇关于C 字符串初始值设定项不包括终止符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!