Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get array size for dynamic created memory

Tags:

c++

arrays

Consider an example:

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

How can I know the size of arr?

like image 802
user204930 Avatar asked Jul 04 '26 11:07

user204930


2 Answers

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

like image 120
Fred Larson Avatar answered Jul 07 '26 00:07

Fred Larson


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();
}
like image 44
Patrick Avatar answered Jul 07 '26 00:07

Patrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!