Why this program is giving this output? Please help! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Why this program is giving this output? Please help!

Program: #include <stdio.h> int main() { char arr[3] = {'b','c','d'}; char str[] = "hello"; printf("%s\n", arr); printf("%s", str); return 0; } Output: bcdhello hello Why is it printing bcdhello instead of bcd?

13th Jan 2021, 3:21 PM
Mahima Rajvir Singh
Mahima Rajvir Singh - avatar
4 Answers
+ 6
Is it ? https://code.sololearn.com/cE3Hs3HrnmXd/?ref=app this program is showing an undefined behaviour The problem here is you are trying to display character array as a string, and according to C, end of string is defined by '\0'(NULL) character. So if you use "%s" format specifier then it will keep on printing till the time it doesn't encounter either a NULL character or an unacessable memory location (will result in segmentation fault in later case)
13th Jan 2021, 3:55 PM
Arsenic
Arsenic - avatar
+ 4
Mahima Rajvir Singh when you increase the size of array and initialize some of it's values, all the rest of the values are by default set to zero. And ASCII value of NULL is also zero thus reading it as character marks end of the string.
13th Jan 2021, 4:12 PM
Arsenic
Arsenic - avatar
+ 3
Arsenic But when we write arr[4], it works fine. But why?
13th Jan 2021, 4:08 PM
Mahima Rajvir Singh
Mahima Rajvir Singh - avatar
+ 3
Arsenic Okay thanks a lot! Extremely helpful! 😊😊
13th Jan 2021, 4:14 PM
Mahima Rajvir Singh
Mahima Rajvir Singh - avatar