在 C++ 中为数组分配特定数量的内存的目的是什么? [英] What is the purpose of allocating a specific amount of memory for arrays in C++?

查看:23
本文介绍了在 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天全站免登陆