The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
This should not be confused with the size of the array that holds the string. For example:
char mystr[100]="test string";
defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.
对无 \0 结尾的字符串调用
strlen
是未定义行为。先分析您的代码:
进一步理解
strlen 说明
字符数组是字符数组,字符串是字符串。只有字符串才有 \0,字符数组没这待遇。这三个代码片段输出的结果,应该都是随机值——恰好从 a 开始偏移的那段内存中有个数据让 strlen 误认为是 \0,于是它就返回了自己读到的字节数。
被踩了一下……可能踩我的人认为,当数组的长度大于字符串实际长度时,编译器会自动在字符串末尾添加 \0。事实上,这依赖于编译器的具体实现,C 标准中对此没有什么说法。