什么是\\ 0符号在C字符串是什么意思? [英] What does the \0 symbol mean in a C string?
问题描述
考虑以下code:
char str[]= "Hello\0";
这是海峡阵列的长度,并与它多少0结束?
What is the length of str array, and with how much 0s it is ending?
推荐答案
sizeof的STR
为7 - 五个字节为你好的文字,再加上明确的NUL终止,加上隐含的NUL终止符。
sizeof str
is 7 - five bytes for the "Hello" text, plus the explicit NUL terminator, plus the implicit NUL terminator.
的strlen(STR)
是5 - 五你好只字节
strlen(str)
is 5 - the five "Hello" bytes only.
这里的关键是,隐含的NUL终止符是的总是的补充 - 即使字符串正好与结束\\ 0
。当然,的strlen
只是停止在第一个 \\ 0
- 它不能分辨
The key here is that the implicit nul terminator is always added - even if the string literal just happens to end with \0
. Of course, strlen
just stops at the first \0
- it can't tell the difference.
有一个例外的隐含NUL终止规则 - 如果明确指定数组大小,字符串将被截断以适应:
There is one exception to the implicit NUL terminator rule - if you explicitly specify the array size, the string will be truncated to fit:
char str[6] = "Hello\0"; // strlen(str) = 5, sizeof(str) = 6 (with one NUL)
char str[7] = "Hello\0"; // strlen(str) = 5, sizeof(str) = 7 (with two NULs)
char str[8] = "Hello\0"; // strlen(str) = 5, sizeof(str) = 8 (with three NULs per C99 6.7.8.21)
这是,然而,很少有用,而且容易错估字符串的长度,并用未终止的字符串结束了。它也禁止在C ++中。
This is, however, rarely useful, and prone to miscalculating the string length and ending up with an unterminated string. It is also forbidden in C++.
这篇关于什么是\\ 0符号在C字符串是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!