Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

In C, strings end at 0 byte. It is automatically there when you have string literal using "", and when you use string functions to modify strings (exception: strncpy).

But your b does not have this 0 byte, so it is not actually a string, it is just a char array. You can’t use string functions like strlen with it!

To put the 0 there, you can do this:

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

Note: Using '\0' instead of just 0 is just cosmetic, making it explicit this is 0 byte value character. Using just 0 is equal syntax, if you prefer that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading