The best way to do this will be by using vectors. They are resizable arrays which handle all the memory management automatically. In this case, you can create a 2-D vector.
However, if for some reason you do not want to use vectors and want to use C-style arrays, then you can do it by creating an array of pointers and allocating different amounts of memory to each one of them. For storing their size, we can follow the strategy of allocating an additional cell in every array which will store the size of that array.
int main()
{
const int no_of_arrays=10;
int array_size[no_of_arrays]= {1,4,2,4,3,6,8,9,1,3}; // Different size for each array
int *p[no_of_arrays]; // An array of pointers
for(int i=0; i<no_of_arrays; i++)
{
p[i]=new int[array_size[i]+1]; // Allocating
p[i][0]=array_size[i]; // The first cell holds the size of the array
for(int j=1; j<=p[i][0]; j++)
{
p[i][j]=10; // Fill the array with the desired values;
}
}
// Display the arrays
for(int i=0; i<no_of_arrays; i++)
{
for(int j=1; j<=p[i][0]; j++)
{
std::cout<<p[i][j]<<" ";
}
std::cout<<"\n";
}
/*
*
* Do your thing with the arrays.
*
*/
// Deallocate the memory allocated to the arrays
for(int i=0; i<no_of_arrays; i++)
{
delete[] p[i];
}
}
However, doing this is not recommended as it can cause lot of problems ( For example memory leaks in case you forget to use delete
after new
). Prefer to use vectors instead in case you don't know the size of the array beforehand.