# Thread: How to get the size of an dynamic array?

1. ## How to get the size of an dynamic array?

I want to find out the size of ptr, i mean what is the ptr[max].

Code:
```#include <iostream>

using namespace std;

int main(void) {
int arraytest[] = { 0, 1, 2, 3, 4, 5, 6 , 7, 8 ,9};
cout << "sizeof(arraytest): " << sizeof(arraytest) << endl; //working
double *ptr = NULL;
int input = 0;
int i = 0;
while (1)
{
cout << "Enter digit, 0 to end." << endl;
cin >> input;
if (input == 0)
{
break;
}
ptr = static_cast <double *> ( realloc(ptr, ((i + 1) * sizeof(*ptr))) );
ptr[i] = i;
i++;
cout << "sizeof(*ptr): " << sizeof(*ptr) << endl; //not working, wrong size
}
free(ptr);
ptr = NULL;
return EXIT_SUCCESS;
}```
For example if I would want to output all items of arraytest I could write
Code:
```	for(int j = 0; j < (sizeof(arraytest) / sizeof(int)); j++) {
cout << arraytest[j] << endl;
}```
Which in find quite generic.

For the dynamic array there is no such nice way. I could only work around and count that manually (variable i).

Is there any nice way like with sizeof?

2. No. Thats why containers like std::vector were invented.

3. Ok, alright.

4. But since you are allocating the dynamic arrray and resizing it manually, one could argue you already know the size of it.

5. I agree with bubba: You have i or i+1 items pointed to by pointer - which of i or i+1 depends on where you "look" - it is i+1 at the return of realloc() until i++, everywhere else there it is i.

[Of course, this is not valid befre i is initialized, and neither is it valid after the call to free - just stating the obvious to prevent some pedant from commenting on this flaw in the above statement. It is fairly common in software engineering to be overly pedantic and detail oriented.]

Of course, like prog-bman said: It is exactly why there are classes that can hold data for you with built-in functions to tell you how many items there are, find where it is, remove stuff, etc, etc. But if you want to keep track of it yourself, then you will have to keep track of the number of items, and there's no shortcut for that.

--
Mats

6. Damn, maybe I just read wrong books and learn stuff I will never really need. Why fight with this, when there is vector.

7. Originally Posted by sept
Damn, maybe I just read wrong books and learn stuff I will never really need. Why fight with this, when there is vector.
Sometimes (most of the time) the right answer is to use "ready made functions", but for several reasons, there may be good reasons to:
1. Understand how things work at a lower level.
2. Be able to write your own code that you have full control over.
3. Write your own base functions.

Most likely you will at some point find a case where the "standard library" doesn't quite do what you need.

--
Mats

8. Also, you should be using new & delete in C++, not malloc(), free()...

Popular pages Recent additions