+ 2

Getting_Very_Wierd_Output

When I am compling the below program the expected output for s variable is "b". But it is getting mixed up with the above strings in the buffer. #include <iostream> #include<string.h>// for string methods. #include<iomanip> using namespace std; int main() { char a[12] ="Hello World"; // cout<<a<<endl; // cin>>setw(12)>>a; // cout<<a<<endl; // cout<<strlen(a)<<endl; char s[]={'b'}; // cout<<strlen(s)<<endl; cout<<s<<endl; return 0; }

23rd Oct 2018, 6:19 PM
Badri
4 Answers
+ 1
Dayala Badrinadh Reddy a is initialized by the copy constructor. Any literal string is appended \0 at the end, when you write: char a[12] = "Hello World"; The entire temporary string is copied to a, including the null terminator. Using list initialization, no temporary is created, and you have to add the null terminator explicitly.
23rd Oct 2018, 11:58 PM
HoĂ ng Nguyễn Văn
HoĂ ng Nguyễn Văn - avatar
0
Yeah But the stack implementation what you said , Is it the way how compiler works on string I mean store strings !? And when we are initialising a char array using {' ',...} we never mentioned '\0' specifically. Because it is said that the compiler takes cares of it and appends '\0' automatically at the end of string initialised that way. Then why are we specifically mentioning above char s[]={..,'\0'}
23rd Oct 2018, 7:17 PM
Badri
0
this is c++ but it's not Python
25th Oct 2018, 2:28 PM
Rahul