Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is that char null terminator is including in the length count

Tags:

c++

c

#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.

like image 958
runcode Avatar asked Feb 16 '13 01:02

runcode


People also ask

Does length count null terminator?

strlen(s) returns the length of null-terminated string s. The length does not count the null character.

Does char include null terminator?

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.

Does string size include null terminator?

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.

Does string length include null character C?

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'.


2 Answers

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. 
like image 131
billz Avatar answered Oct 09 '22 14:10

billz


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.

like image 20
David G Avatar answered Oct 09 '22 16:10

David G