When I run the program, the second printf()
prints string2
with whatever was scanned into string1
attached to the end.
e.g.
In your code
char string2[4]={'1','2','a','b'};
string2
is not null-terminated. Using that array as an argument to %s
format specifier invokes undefined behavior, as it runs past the allocated memory in search of the null-terminator.
You need to add the null-terminator yourself like
char string2[5]={'1','2','a','b','\0'};
to use string2
as a string.
Also, alternatively, you can write
char string2[ ]= "12ab";
to allow the compiler to decide the size, which considers the space for (and adds) the null-terminator.
Same goes for abc
also.
That said, you're scanning into string1
and printing string2
, which is certainly not wrong, but does not make much sense, either.