简体   繁体   English

如何获取动态创建的内存的数组大小

[英]How to get array size for dynamic created memory

Consider an example: 考虑一个例子:

void main()
{
    int *arr;
    arr=new int[10];
}

How can I know the size of arr? 我怎么知道arr的大小?

You have to keep track of it yourself. 你必须自己跟踪它。 I'd recommend making life easier on yourself by using a vector or deque instead. 我建议使用矢量或deque来让自己的生活更轻松。

Two ways (please note that in the first arr is a ptr not an int): 两种方式(请注意,在第一个arr是ptr而不是int):

int main()
{
    const int SIZE = 10;
    int* arr;
    arr = new int[SIZE];

    delete[] arr;
}

or better yet: 或者更好的是:

int main()
{
     std::vector<int> arr( 10 );
     std::size_t size = arr.size();
}

你的数组大小是10。

In deed you can overload new and track allocation size with some static class method. 在契约中,您可以使用一些静态类方法重载新的和跟踪分配大小。 Try to check tools such as LeakTracer . 尝试检查LeakTracer等工具。

Although LeakTracer is not so right implemented tool it provides almost all you need and even beyond this. 虽然LeakTracer不是那么正确的实现工具,但它提供了几乎所有你需要的东西,甚至超出了它。 You simple need to add static method to get allocation size by pointer (not so hard to implement it, just modify 'delete' handler). 你只需要添加静态方法来通过指针获取分配大小(不是很难实现它,只需修改'delete'处理程序)。

you can use sizeof and divide by the size of whatever the array's storing to get the number of items? 你可以使用sizeof并除以数组存储的大小来获得项目数量? something like that 类似的东西

Stroustrupp would tell you to use a container so that you don't get leaks or buffer overruns when accessing it. Stroustrupp会告诉您使用容器,以便在访问它时不会出现泄漏或缓冲区溢出。

Edit for clarity: the first part is an explanation why the editor change his original code from 为清晰起见编辑:第一部分是编辑器更改原始代码的原因

int arr;

to

int* arr;

~~~~~ ~~~~~

When you declare 当你申报时

int arr;

are you making arr an int. 你在做一个int。 It will then hold the pointer to the new array you just created. 然后它将指向您刚刚创建的新数组。 But the size of arr is still size_of(int). 但是arr的大小仍然是size_of(int)。
~~~~~ ~~~~~

I'm guessing that's not what you're asking. 我猜这不是你问的问题。 Are you asking how can you know the size of the array? 你问你怎么知道阵列的大小? You have to keep track of it yourself. 你必须自己跟踪它。

#define ARR_SIZE 10

void main()
{
  int * arr;
  arr = new int[ARR_SIZE];
}

But as Fred said, it would most likely be better to use something else that keeps track for you. 但正如弗雷德所说,使用其他可以追踪你的东西更有可能更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM