Array size question

Hi there,

I know that for an array that is declared like

T array[size]

the size of the array can always be found by using

int size = sizeof(array)/sizeof(T);

However, if the array is declared like

T array* = new T array[size];

there seems to be no way of finding its size since array is now only a pointer. So, to be concrete, is there a way to find the size of an array that is defined dynamically with new?

cheers,
little
From my short experience with pointers, you need to either have a data member in a class or have a initialized and declared variable with the size. The whole point of pointers is to create on-demand memory and move the data easily. As far as what I "think" you're trying to do, try this.

I'm just going to assume that you want an array of ints. Really its not that hard to change what type you want your array to be. If you really don't know beforehand, its never a bad thing to just make a void pointer. Anyways...

1
2
3
int size = 1;
int *array = new int[size];


Say you want to increase the size of the array by one, and assuming that you had initially created an array with the *array pointer, all you would need to do is int *newArray = new int[size + 1] . This will give you a new pointer and a new array one size bigger. (its good practice to just increment your new array by one.)

Hope this helps.
look up vectors.
and when you do int *newArray = new int[size + 1] you need to make sure to delete the old array.
So, to be concrete, is there a way to find the size of an array that is defined dynamically with new?


No there is no such a method. You shall youself keep in mind (in a variable) the size of allocated memory.
On this topic: If there is no way to find the size of the allocated memory, how does the delete[] operator know how much memory to release? I'd say the logical explanation is that it stores it somewhere, but then why wouldn't we be allowed access?
When a memory block is allocated by new it also allocate memory for the block prefix in which it keep the block size. But it is an internal realization of the new and is not an open interface.
Last edited on
Gaminic wrote:
On this topic: If there is no way to find the size of the allocated memory, how does the delete[] operator know how much memory to release? I'd say the logical explanation is that it stores it somewhere, but then why wouldn't we be allowed access?

Because of the way memory is allocated. You may actually get more memory than you asked for. There may be other constraints in play.
Topic archived. No new replies allowed.