Search code examples
c++arrayspointerssizeof

Array of pointers to an array of pointers to int


If i have array of pointer to an array of pointer to int

int **arrs = new int *[n];

and assign each element to new array of pointer to int

for i<n
 arrs[i] = new int[size]

Now, when i try to get size of these arrays, give me wrong value

int size = sizeof(arrs[0])/sizeof(int);

It gives me wrong value. So how can i get the right value ?


Solution

  • You can't. arrs[0] is a pointer, so sizeof(arrs[0]) gives the size of that pointer.

    It comes as a surprise to some that there is no way to get the size of an array from only a pointer to that array. You have to store the size somewhere else.

    In C++ the simplest and best solution is to use std::vector. Why reinvent the wheel? std::vector has everything you would want from a dynamic array, and should be the first choice in this situation.