#include <stdio.h> int main(int argc, char *argv[]) { char s[]="help"; printf("%d",strlen(s)); }
Why the above output is 4, isnt that 5 is the correct answer?
it should be 'h','e','l','p','\0' in memory..
Thanks.
strlen(s) returns the length of null-terminated string s. The length does not count the null character.
Char functions rely on the null terminator, and you will get disastrous results from them if you find yourself in the situation you describe. Much C code that you'll see will use the 'n' derivatives of functions such as strncpy. From that man page you can read: The strcpy() and strncpy() functions return s1.
No, but if you say temp. c_str() a null terminator will be included in the return from this method. It's also worth saying that you can include a null character in a string just like any other character. and not 5 1 as you might expect if null characters had a special meaning for strings.
strlen() function in c The strlen() function calculates the length of a given string. The strlen() function is defined in string. h header file. It doesn't count null character '\0'.
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
counts the elements until it reaches the null character, in which case it will stop counting. It won't include it with the length.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With