+ 1

Why this code prints hello?

char str1[6] = "hello"; char str2[] = "world"; printf("%s", str1, str2);

31st Aug 2020, 11:27 AM
Gujjula Pradeep Reddy
Gujjula Pradeep Reddy - avatar
5 odpowiedzi
+ 3
Let's have a look at the printf function here. The printf in general is responsible only to print the string included, that's it. If we want to print a data type then we specify the format. Now here, in the string provided, there is only one %s string format specifier. Hence the function checks if there is *a* string data type, and takes the first one and leaves out the rest because it's not needed. So it only prints hello. If you want to print "world" too then put two format specifiers like, "%s%s".
31st Aug 2020, 11:51 AM
विशेष
विशेष - avatar
+ 2
विशेष Nice explanation, thank u
31st Aug 2020, 11:57 AM
Gujjula Pradeep Reddy
Gujjula Pradeep Reddy - avatar
+ 1
That will give you an error, bcoz you have passed two values in printf function, and you have used only one format specifier (%s), if you want to print "hello word" than use two format specifier. Like that : printf ("%s %s",stri,str2), you will get expected output..
31st Aug 2020, 2:45 PM
Rupali Haldiya
Rupali Haldiya - avatar
0
Why don't you run it yourself on playground?
31st Aug 2020, 11:29 AM
Raj Chhatrala
Raj Chhatrala - avatar