动态分配数组的有趣行为 [英] Interesting behavior with dynamically allocated array

查看:50
本文介绍了动态分配数组的有趣行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在使用动态分配的数组,并将其设置为可容纳5个元素,因此应为0-4。我在必要时做了一个保留它的函数,但是我想看看是否在给[5]的数组赋值时遇到程序崩溃。但是,直到[6]都没有错误。

So I'm working with a dynamically allocated array, and I've set it to hold 5 elements, which should thus be 0-4. I made a function to reserve it if necessary, but I wanted to see if I was getting the program crash I expected when I assigned a value to the array at [5]. But, no error, not until [6].

这是我的代码:

int* dynamic_arr;
dynamic_arr = new int[5];

for(int i = 0; i <= 100; i++){
    dynamic_arr[i] = i;
    used++;
    cout << dynamic_arr[i]<<endl;
}

这是输出:

0 //i[0]
1 //i[1]
2 //i[2]
3 //i[3]
4 //i[4]
5 //i[5]  <-- should be out of range

之后它崩溃了。

为什么我可以为数组的一部分分配一个值, ,因为缺少更好的条件而超出范围?

Why am I able to assign a value to a portion of the array that is, well, out of range for lack of a better term?

谢谢

OpSrcFTW

编辑:感谢大家的回答,谢谢。很抱歉,我会在发布前阅读更多内容,以便下次快速回答。

Appreciate the answers guys, thanks. I'll read more before posting for a quick answer next time, sorry.

推荐答案

访问数组末尾会产生未定义的行为。它不一定会导致崩溃。任何事情都可能发生。

Accessing beyond the end of an array produces undefined behavior. It does not necessarily produce a crash. Anything can happen.

这篇关于动态分配数组的有趣行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆