查找动态分配数组的大小 [英] Finding size of dynamically allocated array

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

问题描述

为什么无法获得以此方式分配的缓冲区的长度.

Why is it not possible to get the length of a buffer allocated in this fashion.

AType * pArr = new AType[nVariable];

当同一数组被释放时

delete [] pArr;

运行时必须知道要释放多少.有什么方法可以在删除数组之前访问长度.如果没有,为什么没有提供这样的API来获取长度?

the runtime must know how much to deallocate. Is there any means to access the length before deleting the array. If no, why no such API is provided that will fetch the length?

推荐答案

在删除数组之前,有什么方法可以访问长度吗?

Is there any means to access the length before deleting the array?

不.无法确定.
该标准不需要实现记住并提供通过new请求的元素数量的详细信息.
该实现可以简单地在分配的内存块的末尾插入特定的位模式,而不用记住元素的数量,并且可以在释放内存的同时简单地查找模式. 简而言之,这仅仅是一个植入细节.

No. there is no way to determine that.
The standard does not require the implementation to remember and provide the specifics of the number of elements requested through new.
The implementation may simply insert specific bit patterns at end of allocated memory blocks instead of remembering the number of elements, and might simply lookup for the pattern while freeing the memory.
In short it is solely an imlpementation detail.

顺便提一下,实际上有2种方法可以解决此问题:

On a side note, There are 2 options to practically overcome this problem:

  1. 您可以简单地使用std::vector来提供像size()
  2. 这样的成员函数.
  3. 您可以自己简单地进行簿记.
  1. You can simple use a std::vector which provides you member functions like size() or
  2. You can simply do the bookkeeping yourself.

new 至少根据需要分配足够的内存.
您已经知道所需的内存量,因此可以轻松计算长度.您可以使用sizeof查找每个项目的大小.

new atleast allocates enough memory as much as you requested.
You already know how much memory you requested so you can calculate the length easily. You can find size of each item using sizeof.

Total memory requested / Memory required for 1 item = No of Items

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

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