2

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!

awesoon
  • 32,469
  • 11
  • 74
  • 99
The Newbie Toad
  • 186
  • 2
  • 15
  • Note: The indicated "duplicate" question has meaningful, but incomplete, answers because the question is specific to a related, but different, programming language -- as well as a different allocation function. – Brent Bradburn May 22 '13 at 14:12

3 Answers3

8

There is not a standard way get the size of an array allocated with new.

A better approach to array allocation is std::vector, which does have a size() member -- and it automatically cleans up after itself when it goes out of scope.

Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173
5

Short answer: No.

Use std::vector instead.

yzn-pku
  • 1,082
  • 7
  • 14
1

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.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227