简体   繁体   中英

How is the output for the following cpp program justified

char a[4];
cin >> a;
char b[3];
cin >> b;
cout << a << "\n";
cout << b;

input: india lockdown Gives me output: kdown lockdown

while hard coding the char array like

char a[]= "india"
char b[]= "winner"
cout << a <<" " << b;

gives me the expected result can you please explain the reason of the unexpected results.... Thanks

What you observe is a book example of buffer overflow. User input doesn't fit the buffer, and you get garbage written into some other variables on the stack. C++ standard says this is UB (undefined behavior), so many things may happen.

In your second example, the size of the arrays is chosen automatically to fit the strings (including null-character terminators).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM