I’d like your help with understand what can be an input from a user to the following program that can make the output:U%ae'$ffq' ong string
int main(void) {
int i=0;
char j[22]="This is a long string", k[3];
scanf("%2s ", k);
sprintf(j, k);
printf("%s", j);
for (; i< 21; printf("%c", j[i++]))
;
return 1;
}
I don’t understand couple of things:
k can get only two chars from the user- Is this what "%2s" means, no? and then writes into the array pointed by j the content pointed by the array k, so j is not pointed to k, but if we’ll j[5] we’ll still get i. so I don’t understand how can we get this input whatsoever since the input would be chopped to two chars j[0], j[1] would be the two chars from the input and the rest of j[i] would be the original rest of “This is a long string”.
I’m only guessing here, but the problem is probably with the loop. You do not check for the string terminator, but print all of the array regardless of if the string has ended or not.
If you change the loop to this:
You should get the expected output.
(Note: I also changed
21to22which is the size of the array. You can of course doi <= 21as that is the same.)Edit: Rereading the question after the comment from hmjd.
If the input as read by
scanfcontains a percentage ('%') character the call tosprintfafterwards will try to parse it as a formatting code. If I test this program with the input%d123, thenkwill be"%d"as expected, but the resulting arrayjwill be"192795408\0long string".