#include
int main(int argc, char *argv[]) {
char s[]=\"help\";
printf(\"%d\",strlen(s));
}
Why the above output is 4, isn
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.
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'};
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.
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.
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).