1

I have the following declaration:

char ***a; a = new char**[1]; a[0] = new char*[2]; a[0][0] = "Dynamic"; a[0][1] = "Array"; 

Now I need to find the number of elements in "a" as well as in "a[0]". How can I do this in C or C++?

5
  • 1
    Related: stackoverflow.com/a/8320324/951890 Commented Oct 5, 2013 at 16:57
  • possible duplicate of Is this a good way to find the length of a dynamically allocated array? Commented Oct 5, 2013 at 16:58
  • no_of_elements = sizeof( array ) / sizeof( array[0] ); Commented Oct 5, 2013 at 16:58
  • 2
    @Vandesh No, there is no way to get size of a dynamic allocation from a pointer Commented Oct 5, 2013 at 17:05
  • 1
    You cannot do that. This is one of the many drawbacks of dynamically allocated plain arrays. Commented Oct 5, 2013 at 17:24

1 Answer 1

2

As far as I know there is no way to find number of elements in dynamically allocated array, when you pass the first element of the array as pointer to some function/method. Best practice is to avoid usage of such arrays, and when you use it, pass the number of allocated elements together with the pointer.

void doSomething(int * p, int elms) { //... } int main(){ int * arr = new int[10]; doSomething(arr, 10); } 
Sign up to request clarification or add additional context in comments.

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.