vishal kumar
vishal kumar

Reputation: 41

dynamic memory allocation of 2d array in which columns are of different size

i want to create a 2d array dynamically in c++ language. But in that 2d array columns should be of different size. i mean to say that 2d array should not be in M * N.

It should be something like....

1 2 next line
3 4 5 next line
2 3 4 5 next line
5 next line
4 5 7

I am able to create 2d array in above manner but how to display content of array continously create a problem for me. Please anyone explain me how to come up with this problem.

Upvotes: 0

Views: 1345

Answers (1)

Anmol Singh Jaggi
Anmol Singh Jaggi

Reputation: 8576

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.

Upvotes: 5

Related Questions