简体   繁体   中英

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));

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM