我无法理解此代码输出的异常行为。 它打印:
hellooo
monusonuka
代码在这里:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
printf(" hellooo \n");
char name[7]="sonuka";
char name1[4]={'m','o','n','u'};
printf("%s",name1);
system("pause");
return 0;
}
最佳答案
您的 name1
数组未以零字符结尾 ('\0'
)。 printf
函数打印字符,直到找到零。在您的情况下,它超过了数组的末尾。发生的是未定义的行为。一个可能的结果是其他变量或垃圾被打印到屏幕上,直到最终 \0
在内存中的其他地方被击中,但任何事情都可能发生,包括你的程序崩溃。
关于c++ - C++中出现这种异常输出的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12115683/