Problem while printing a string
I'm writing a C Code in which开发者_StackOverflow my array of length 2 char contains String My But while printing it to the Screen using puts(). I'm getting this output
My £■ 0√"
What is the reason for such codes ???
And if my array length is 2 then How can i get output of length 2+ ???
sounds like you are missing the null terminator - the string needs to be three chars "m', 'y', '\0'
If you've explicitly set the length of the string to 2, you're not leaving room for a NUL terminator, which is what puts
uses to find the end of the string. Since you don't have one, it'll continue printing out the contents of memory following the string you defined, until it gets to a byte in memory that happens to contain a 0.
To avoid that, you generally should not specify the length when you're creating a string literal:
char string[2] = "My"; // avoid this
char string2[] = "My"; // use this instead.
It's been a while since I did C. But I suspect that your character array doesn't end with a null character. So you need to end your array with '\0'
Your array length should be at least 3, one for each character and one for a \0 character.
make sure you've got the terminating char.
精彩评论