Array size question

Apr 13, 2012 at 9:09am
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
Apr 13, 2012 at 9:18am
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.
Apr 13, 2012 at 9:59am
look up vectors.
and when you do int *newArray = new int[size + 1] you need to make sure to delete the old array.
Apr 13, 2012 at 1:05pm
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.
Apr 13, 2012 at 1:12pm
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?
Apr 13, 2012 at 3:58pm
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 Apr 13, 2012 at 3:59pm
Apr 13, 2012 at 9:15pm
Apr 13, 2012 at 9:28pm
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.