【问题标题】:is that char null terminator is including in the length count是 char 空终止符是否包含在长度计数中
【发布时间】:2013-02-16 01:24:00
【问题描述】:
#include <stdio.h>

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

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

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

谢谢。

【问题讨论】:

  • 如果你使用sizeof(s) / sizeof(char),你会得到你期望的答案。
  • @WaleedKhan: True -- 当代码如上所写时。不幸的是,看似微不足道的更改(例如,char *s="help";)会破坏这一点,因此您需要非常小心。只要我们在它上面,sizeof(char) 就被定义为始终为 1,所以只需 sizeof(s) 就可以满足现在的代码。
  • strlen 的文档在这件事上是否不清楚?

标签: c++ c


【解决方案1】:

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

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

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

char s[]="help";
sizeof(s) should return 5.

【讨论】:

  • 评论有误。 sizeof 确实返回 5:pastebin.com/94AbKunk
  • 注意如果数组的大小是已知的,例如char s[9] = "help",那么sizeof 将是9 而不是5,因为其余的存储将被隐式初始化为\0
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      现在是 4。

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

      【讨论】:

        【解决方案5】:

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

        对于此类问题,我建议您参考 link 之类的参考资料。

        明确表述为:

         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-03-27
          • 1970-01-01
          • 2011-06-01
          • 2021-11-06
          • 2012-06-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多