Hi there,

I am having problem with deallocating string two-dimensional dynamic array. My program works fine but for some conditions such as when row size is greator than column size in 2d dynamic array, the program crashes when it goes into destructor.

My program is as follows :

#include <iostream>
#include <string>

using namespace std;

class Str2DimDynArr
{
    private:

        int rowSize, colSize;
        string **arr;

    public:

        Str2DimDynArr()
        {
            cout<<"Enter row size of array : "<<flush;
            cin >> rowSize;
            cout<<"Enter column size of array : "<<flush;
            cin >> colSize;

            arr = new string*[rowSize];
            for(int i=0; i<rowSize; i++)
                arr[i] = new string[colSize];

            cout<<""<<endl; //new line
        }

        //destructor
        ~Str2DimDynArr()
        {
            cout<<"\nEntered in desctructor !!"<<endl;

            //de-allocate two dimensional dynamic string array
            for(int i=0; i<colSize; ++i)
                delete[] arr[i];

            delete[] arr;

            cout<<"\nProgram terminated !!"<<endl;
        }

        void populateArr()
        {
            for(int row=0; row<rowSize; row++)
                for(int col=0; col<colSize; col++)
                {
                    cout<<"Enter string in array : "<<flush;
                    cin >> arr[row][col];
                }

            cout<<""<<endl; //new line
        }

        void printArr()
        {
            cout<<"\nArray : \n"<<endl;
            for(int row=0; row<rowSize; row++)
            {
                for(int col=0; col<colSize; col++)
                {
                    cout<<arr[row][col] <<" ";
                }
                cout<<""<<endl;
            }
        }
};

int main()
{
    Str2DimDynArr ob;

    ob.populateArr();
    ob.printArr();

    return 0;
}

Please check my destructor code and kindly tell me if it is ok for deallocating string 2d dynamic arrays. Also tell me why my program is crashing in some cases. Thanks !

Line 35 should use rowSize not colSize. This is because you are stepping through each row and deleting all of the columns.

Thanks buddy, now it makes sense :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.