+ 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?
4 Antworten
+ 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)
+ 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.
+ 3
Arsenic But when we write arr[4], it works fine. But why?
+ 3
Arsenic Okay thanks a lot! Extremely helpful! 😊😊