46
#include <stdio.h>

int main(int argc, char *argv[]) {
   char s[]="help";
   printf("%d",strlen(s));  
}

为什么上面的输出是 4,那不是 5 是正确的答案吗?

它应该是 'h','e','l','p','\0' 在内存中..

谢谢。

4

5 回答 5

67

strlen:返回给定字节字符串的长度,不包括空终止符;

char s[]="help";
strlen(s) should return 4.

sizeof:返回给定字节字符串的长度,包括空终止符;

char s[]="help";
sizeof(s) should return 5.
于 2013-02-16T01:27:07.080 回答
9

strlen计数元素直到它到达空字符,在这种情况下它将停止计数。它不会包含在长度中。

于 2013-02-16T01:25:14.847 回答
4

strlen()不计算数组中的字符数(事实上,这甚至可能是不可知的(如果你只有一个指向内存的指针,而不是数组)。正如你所发现的,它确实计算了最多但不包括空字符的字符。考虑char s[] = {'h','i','\0','t','h','e','r','e'};

于 2013-02-16T01:28:29.363 回答
2

是4。

strlen() 计算最多但不包括值为 0 的第一个字符的字符数 - nul 终止符。

于 2013-02-16T01:25:23.523 回答
2

strlen(const char* ptr)通过计算从开始直到达到零的非零元素来返回字符串的长度。所以'\0'不算。

对于此类问题,我建议您参考参考链接

它明确表示为:

 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).
于 2013-02-16T03:44:01.230 回答