tags:

views:

98

answers:

4

I'm writing a C Code in which 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+ ???

+6  A: 

sounds like you are missing the null terminator - the string needs to be three chars "m', 'y', '\0'

pm100
yeh you are right for this case. but my actual problem was not only to display but also to compare it with other string.say I'm writing if(strcmp(tempBuffer, "My") == 0){ printf("True"); }in that case the presence of \0 won't give me correct answer..is there any other way to do it ???
Mew 3.2
@Mew 3.2: int memcmp(const void *s1, const void *s2, size_t n); This function does not require null terminated sides, but requires a size.
Notinlist
@Mew 3.2 - `char tmpBuffer[3] = "My"; strcmp(tmpBuffer, "My") == 0;` yields the proper results. C strings (`"anything"`) automatically include a nul-terminator.
Chris Lutz
strcmp will do the right thing, both strings must be null terminated.If they are not then bad things will happen
pm100
@Mew 3.2: `strncmp`.
jamesdlin
+1  A: 

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.

John Boker
+2  A: 

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'

Vivin Paliath
To answer your other question, as to the reason why you're getting garbage characters, puts is basically printing everything until it finds a '\0'.
Vivin Paliath
+5  A: 

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.
Jerry Coffin
well actually I'm reading this content from the file for tokenization purpose. And for reading the content I'm suppose to put the length in the beginning only...And if i'm putting the length in the beginning then the problem is as I've commented above...
Mew 3.2