You are here:

C++/C++ pointers array


I wish to grow a dynamic array of pointers,
so i thought of copying the pointers to temp pointers array
and than to double the size of the original array,
but I think i should "free" the original before growing it,
how can i do it without deleting the data that the pointer leads,
i thought of setting each index to point to null and than delete the whole array, (and than growing the array and re copying) will it works?, have a better solution?

Thank you!

std::size_t array_size = 100 ;
int** dyn_array = new int* [array_size] ;

for( std::size_t i = 0 ; i < array_size ; ++i )
       dyn_array[i] = new int(i*i*i) ;

// grow dyn_array to double the current size
       std::size_t new_size = array_size * 2 ;
       int** temp = new int* [ new_size ] ; // allocate memory for new array

       for( std::size_t i = 0 ; i < array_size ; ++i ) // copy contents to new array
         temp[i] = dyn_array[i] ;

       for( std::size_t i = array_size ; i < new_size ; ++i ) // set remaining pointers to null
         temp[i] = 0 ;

       delete[]  dyn_array ; // release memory for old array

       dyn_array = temp ; // dyn_array is now the new array
       array_size = new_size ; // and its size is the new size


All Answers

Answers by Expert:

Ask Experts




my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.


about 15 years or so

post graduate engineer

©2016 All rights reserved.