Search code examples
arrayscstringcharacterstrlen

Inaccurate length of string when using 'strlen'


I am getting inaccurate string length when printing the length of a string using the strlen function.

I am getting the output for string a as 5 (which is correct), but when I am printing the length of string b, the output comes out to be 10 (which should be 5).

Here is the code snippet:

char a[] = "Yolow";
char b[] = {'H', 'e', 'l', 'l', 'o'};
printf("len = %d\n", strlen(a));
printf("len = %d", strlen(b));

Solution

  • Here's the original:

    char b[] = {'H', 'e', 'l', 'l', 'o'};
    

    and here's a fix that turns an array of characters into a (null terminated) "string":

    char b[] = {'H', 'e', 'l', 'l', 'o', '\0' }; // add ASCII 'NUL' to the array
    

    or, alternatively:

    char b[] = {'H', 'e', 'l', 'l', 'o',   0 }; // add zero to the array