什么是用C ++数组分配内存的具体数额的目的是什么? [英] What is the purpose of allocating a specific amount of memory for arrays in C++?

查看:96
本文介绍了什么是用C ++数组分配内存的具体数额的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是学生承担数据结构的一类在C ++中这学期我碰到的东西,我不太明白,今晚就来了。说我要创建一个指向在堆上数组:

I'm a student taking a class on Data Structures in C++ this semester and I came across something that I don't quite understand tonight. Say I were to create a pointer to an array on the heap:

int* arrayPtr = new int [4];

我可以通过访问该数组指针语法

I can access this array using pointer syntax

int value = *(arrayPtr + index);

但如果我分配给数组的空间结束后立即添加另一种价值的存储位置,我会再能访问它。

But if I were to add another value to the memory position immediately after the end of the space allocated for the array, I would then be able to access it

*(arrayPtr + 4) = 0;
int nextPos = *(arrayPtr + 4);
//the value of nextPos will be 0, or whatever value I previously filled that space with

在*内存(arrayPtr + 4)的立场是过去分配给数组空间的结尾。但据我了解,上面还不会引起任何问题。所以,除了它是C ++的要求,宣布当他们为什么甚至给数组特定的大小?

The position in memory of *(arrayPtr + 4) is past the end of the space allocated for the array. But as far as I understand, the above still would not cause any problems. So aside from it being a requirement of C++, why even give arrays a specific size when declaring them?

推荐答案

当你走过去的分配内存的结束,实际上您访问的其他对象(或内存是免费的,现在的内存,但可能会在以后更改)。因此,它的因为你的问题。特别是如果你会试着写点东西吧。

When you go past the end of allocated memory, you are actually accessing memory of some other object (or memory that is free right now, but that could change later). So, it will cause you problems. Especially if you'll try to write something to it.

这篇关于什么是用C ++数组分配内存的具体数额的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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