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

runcode
  • 3,533
  • 9
  • 35
  • 52
  • 6
    If you used `sizeof(s) / sizeof(char)` you would get the answer you expect. – Waleed Khan Feb 16 '13 at 01:27
  • 4
    @WaleedKhan: True -- when the code is written as above. Unfortunately, seemingly trivial changes (e.g., `char *s="help";`) will break that, so you need to be pretty careful with it. As long as we're at it, `sizeof(char)` is defined to always be 1, so simply `sizeof(s)` would be fine for the code as it is right now. – Jerry Coffin Feb 16 '13 at 01:45
  • 2
    Was the documentation for strlen unclear on this matter? – Rob Kennedy Feb 16 '13 at 04:46

5 Answers5

75

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.
billz
  • 44,644
  • 9
  • 83
  • 100
  • 1
    Comments are wrong. `sizeof` does return 5: http://pastebin.com/94AbKunk – daaku Nov 04 '16 at 19:03
  • 2
    Note If the size of the array is known, for example `char s[9] = "help"` then `sizeof` will be 9 not 5 because the rest of the storage will be implicitly initialized with `\0`. – Rain Jul 12 '20 at 03:17
11

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.

David G
  • 94,763
  • 41
  • 167
  • 253
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'};

Chris Hartman
  • 167
  • 1
  • 10
4

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.

nos
  • 223,662
  • 58
  • 417
  • 506
3

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).
phoeagon
  • 2,080
  • 17
  • 20