开发者

How to get array size for dynamic created memory

Consider 开发者_如何学Can example:

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

How can I know the size of arr?


You have to keep track of it yourself. I'd recommend making life easier on yourself by using a vector or deque instead.


Two ways (please note that in the first arr is a ptr not an 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();
}


Size of your array is 10.


In deed you can overload new and track allocation size with some static class method. Try to check tools such as LeakTracer.

Although LeakTracer is not so right implemented tool it provides almost all you need and even beyond this. You simple need to add static method to get allocation size by pointer (not so hard to implement it, just modify 'delete' handler).


you can use sizeof and divide by the size of whatever the array's storing to get the number of items? something like that

Stroustrupp would tell you to use a container so that you don't get leaks or buffer overruns when accessing it.


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. It will then hold the pointer to the new array you just created. But the size of arr is still 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜