C++为什么make new int是错误的?

Fra*_*tra -6 c++ arrays pointers

为什么我的代码错误?

int *x ;
x = new int[5];
x[0] = 3;
x[1] = 4;
x[2] = 5;
x[3] = 1;
x[4] = 2;
x[5] = 11;
x[6] = 90;
int *y ;
y = new int[5];
cout << "if no error, then this command should be run" << endl;
Run Code Online (Sandbox Code Playgroud)

但输出是:

进程在0.07883秒后退出,返回值为3221226356

按任意键继续 ...

Sou*_*osh 6

在编写代码之前,请考虑一下逻辑.如果你可以为5 ints 分配空间然后直接进行存储10(或任何超过5个元素的东西),那么,首先分配任何东西的重点是什么?

你在这里看到的是内存溢出,它会调用未定义的行为.不要那样做.

详细说明,在基于0的索引系统上,上述情况的有效索引将为0到4,除此之外的任何内容都将访问超出绑定的内存,从而调用UB.