The size of a string literal is the number of characters in it including the trailing null byte that is added. If there embedded nulls in the string, they are immaterial; they get counted. It is unrelated to strlen()
except that if the literal includes no embedded nulls, strlen(s) == sizeof(s) - 1
.
printf("%zu
", sizeof("S65AB")); // 5: '65' is a single character
printf("%zu
", sizeof("S65AB")); // 6
printf("%zu
", sizeof("S65AB")); // 6: '65' is a single character
printf("%zu
", sizeof("S65AB")); // 7: '6' and '5' are single chars
printf("%zu
", sizeof("S65AB")); // 6: '5' is a single character
printf("%zu
", sizeof("S65AB")); // 7
Note that '377'
is a valid octal constant, equivalent to 'xFF'
or 255. You can use them in strings, too. The value ''
is only a special case of a more general octal constant.
Note that sizeof()
evaluates to a value of type size_t
, and the correct formatting type qualifier in C99 and C11 for size_t
is z
, and since it is unsigned, u
is more appropriate than d
, hence the "%zu
"
format that I used.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…