sizeof str - 7 - five bytes for the text "Hello", plus an explicit NUL terminator plus an implicit NUL terminator.
strlen(str) - 5 - only five bytes of "Hello".
The key point here is that the implicit terminator nul is always added, even if the string literal ends 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 size of the array, the string will be truncated to match:
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, however, is rarely useful and prone to calculate the length of the string and end with an inexhaustible string. This is also forbidden in C ++.
bdonlan Jan 17 '11 at 9:05 2011-01-17 09:05
source share