Search code examples
cstring-length

strlen() counts characters even after the null terminator


#include<stdio.h>
#include<string.h>

int main() {
char a[100]="1234\0567"; //Answer: 6
int len=strlen(a);
printf("%d",len); 
}

This code prints 6 as the answer. Shouldn't it print 4 since strlen returns the count until the null character is encountered?

However when a space is included between \0 and 5. It returns 4 as the answer

char a[100]="1234\0 567"; //Answer: 4

Am I missing something?


Solution

  • You first version has the octal number \056 not the \0 character

    Edit: in the similar situations use \000 octal sequence instead:

    /* from your example*/ char a[100]="1234\000567";