Creation of Dynamic Array of Dynamic Objects in C++

If you are using c++ then you shouldn’t reinvent the wheel, just use vectors:

#include <vector>

std::vector< std::vector< Stock > > StockVector;

// do this as many times as you wish
StockVector.push_back( std::vector< Stock >() );

// Now you are adding a stock to the i-th stockarray
StockVector[i].push_back( Stock() );

Edit:

I didn’t understand your question, if you just want to have and array of arrays allocated on the heap just use:

Stock** StockArrayArray = new Stock*[n]; // where n is number of arrays to create
for( int  i = 0; i < n; ++i )
{
    StockArrayArray[i] = new Stock[25];
}

// for freeing
for( int i = 0; i < n; ++i )
{
    delete[] StockArrayArray[i];
}
delete[] StockArrayArray;

Leave a Comment