字符串字面量\0表示什么? [英] What does the symbol \0 mean in a string-literal?
问题描述
考虑以下代码:
char str[] = "Hello\0";
str数组的长度是多少,以0结尾多少?
What is the length of str array, and with how much 0s it is ending?
推荐答案
sizeof str
是7到5个字节,用于 Hello文本,外加显式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-五个 Hello
strlen(str)
is 5 - the five "Hello" bytes only.
这里的关键是总是添加隐式nul终止符 -即使字符串文字恰好以<$结尾c $ c> \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表示什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!