在c ++中出现这种异常输出的原因

sha*_*lki 1 c++ printf

我无法理解此代码输出的异常行为.它打印:

 hellooo
monusonuka
Run Code Online (Sandbox Code Playgroud)

代码在这里:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

您的name1数组不以零字符('\0')终止.该printf函数打印字符,直到找到零.在你的情况下,它超过了数组的末尾.会发生什么是未定义的行为.可能的结果是其他变量或垃圾被打印到屏幕上,直到最终\0内存中的某个地方被击中,但任何事情都可能发生,包括程序崩溃.