What does the symbol \0 mean in a string-literal?

后端 未结 6 1912
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 12:26

Consider following code:

char str[] = \"Hello\\0\";

What is the length of str array, and with how much 0s it is ending?

6条回答
  •  盖世英雄少女心
    2020-11-27 12:46

    sizeof str is 7 - five bytes for the "Hello" text, plus the explicit NUL terminator, plus the implicit NUL terminator.

    strlen(str) is 5 - the five "Hello" bytes only.

    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.

    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)
    

    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++.

提交回复
热议问题