When I run the program, the second printf()
prints string2
with whatever was scanned into string1
attached to the end.
e.g. 123
was scanned into string1
then it prints: Is before "12ab123"
.
as opposed to 12ab
.
Why not just "12ab"
?
char string1[MAX_STR_LEN];
char string2[4]={'1','2','a','b'};
char five='5';
char abc[3]={'a','b','c'};
printf("Enter a string:");
scanf("%s", string1);
printf("Is before \"%s\":",string2);
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 zeroSo 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
Or you could define the array that includes the terminating zero. For example
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
or without braces