The question makes no sense, because you cannot ask why something is not working right without explaining what do you want to achieve and what should be expected as "right".
Nevertheless, looking at the code shows that
string2
has undetermined last character. Most C function assumes that this character should be null. As null character is missing, the code of
printf
"does not know where to stop" and may print some garbage. This should answer your question.
Please see:
http://en.wikipedia.org/wiki/Null-terminated_string[
^].
You need to add
string2[4]
to 0 (of course, not '0'!). But the practical initialization should be
char* string2 = "Test";
In this case, the compiler adds a null character at the end, and specification of exact length if not needed. Well, all this stuff is a great lame and a real curse of programming, a source of all kinds of bugs and exploits, but this is how those C functions were historically created and are still used by now, with some minor replacements of some functions with some safer ones…
—SA