Is there a function (that could be written) which allows to know the size of an array defined with new:
int *a=new int[3];
*a=4;
*(a+1)=5;
*(a+2)=6;
Thanks!
Is there a function (that could be written) which allows to know the size of an array defined with new:
int *a=new int[3];
*a=4;
*(a+1)=5;
*(a+2)=6;
Thanks!
It would be possible to write a function for this. But in the real world, it's a poor idea.
Although the act of calling new most likely stores the number of elements in the array that is allocated (or at least, the size of the actual allocation underneath it), there is no way that you can get that information in a way that doesn't rely on knowing how new works on your particular system, and that could change if you compile your code differently (e.g. debug or release version of the code), change version of the compiler (or runtime library), etc, etc.
Using the std::vector as mentioned is a much better way, since you then ALSO don't have to worry about freeing your array somewhere else.
If, for some reason, you don't want to [or have been told by your tutor, that you can't] use std::vector, you need to "remember" the size of the allocation.