考虑以下代码:
char str[] = "Hello\0";
str 数组的长度是多少,以多少个 0 结尾?
最佳答案
sizeof str
为 7 - “Hello”文本的五个字节,加上显式 NUL 终止符,加上隐式 NUL 终止符。
strlen(str)
为 5 - 仅五个“Hello”字节。
这里的关键是隐式 nul 终止符总是被添加 - 即使字符串文字恰好以 \0
结尾。当然,strlen
只是停在第一个 \0
- 它无法区分。
隐式 NUL 终止符规则有一个异常(exception) - 如果您明确指定数组大小,则字符串将被截断以适应:
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++ 中也是禁止的。
https://stackoverflow.com/questions/4711449/