When I run the program, the second printf()
prints string2
with whatever was scanned into string1
attached to the end.
e.g.
If the format specifier %s
does not have the precision flag then the function outputs characters until it encounteres zero character '\0'
Character array string2
is defined such a way that it does not have the terminating zero
char string2[4]={'1','2','a','b'};
So the function outputs characters beyond the array until it meets zero character.
You could use the precision flag that to specify explicitly how many characters you are going to output. For example
printf("Is before \"%4.4s\":",string2);
Or you could define the array that includes the terminating zero. For example
char string2[5] = { '1', '2', 'a', 'b', '\0' };
Take into account that in this case the size of the array if it is specified shall be equal at least to 5 ( though the size can be greater than 5; in this case other characters that do not have initializers will be zero-initialized)
or simply
char string2[] = { "12ab" };
or without braces
char string2[] = "12ab";