is that char null terminator is including in the length count

后端 未结 5 1832
春和景丽
春和景丽 2020-12-24 05:37
#include 

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

Why the above output is 4, isn

相关标签:
5条回答
  • 2020-12-24 05:49

    strlen: Returns the length of the given byte string not including null terminator;

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

    sizeof: Returns the length of the given byte string, include null terminator;

    char s[]="help";
    sizeof(s) should return 5.
    
    0 讨论(0)
  • 2020-12-24 05:53

    strlen() does not count the number of characters in the array (in fact, this might not even be knowable (if you only have a pointer to the memory, instead of an array). It does, as you have found out, count the number of characters up to but not including the null character. Consider char s[] = {'h','i','\0','t','h','e','r','e'};

    0 讨论(0)
  • 2020-12-24 05:59

    strlen counts the elements until it reaches the null character, in which case it will stop counting. It won't include it with the length.

    0 讨论(0)
  • 2020-12-24 06:06

    It's 4.

    strlen() counts the number of characters up to, but not including, the first char with a value of 0 - the nul terminator.

    0 讨论(0)
  • 2020-12-24 06:13

    strlen(const char* ptr) returns the length of the string by counting the non-zero elements starting at until reaches zero. So '\0' doesn't count.

    I recommend that you consult the reference like link for questions like this.

    It's clearly stated as:

     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).
    
    0 讨论(0)
提交回复
热议问题