简体   繁体   English

以下cpp程序的output如何证明合理

[英]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输入:印度锁定给我 output:kdown 锁定

while hard coding the char array like同时对 char 数组进行硬编码,例如

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. C++ 标准说这是 UB(未定义的行为),所以可能会发生很多事情。

In your second example, the size of the arrays is chosen automatically to fit the strings (including null-character terminators).在您的第二个示例中,自动选择 arrays 的大小以适合字符串(包括空字符终止符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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