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!

1
  • 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. Commented May 22, 2013 at 14:12

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

5

Short answer: No.

Use std::vector instead.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.