dimanche 9 août 2020

2d dynamic array memory deallocation? [duplicate]

#include<iostream>
class matrix
{
    int row, column;
    int **m;
public:
    matrix(int x, int y)
    {
        row = x;
        column = y;
        m = new int*[row];
        for (int i = 0; i < row; i++)
        {
            m[i] = new int[column];
        }
    }
    friend std::istream& operator >>(std::istream&, matrix&);
    friend std::ostream& operator <<(std::ostream&, matrix&);
    matrix operator +(matrix);
    ~matrix()
    {
        for (int i = 0; i < row; i++)
        {
            delete[] m[i];
        }
        delete[] m;
    }
};
matrix matrix::operator +(matrix m1)
{
    matrix temp(3, 3);
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < column; j++)
        {
            temp.m[i][j] = m[i][j] + m1.m[i][j];
        }
    }
    return temp;
}
std::istream& operator >>(std::istream &input, matrix &m1)
{
    std::cout << "Enter matrix Elements:" << "\n";
    for (int i = 0; i < m1.row; i++)
    {
        for (int j = 0; j < m1.column; j++)
        {
            input >> m1.m[i][j];
        }
    }
    return input;
}
std::ostream& operator <<(std::ostream &output, matrix &m1)
{
    output << "Data present in Matrix:" << std::endl;
    for (int i = 0; i < m1.row; i++)
    {
        for (int j = 0; j < m1.column; j++)
        {
            output << m1.m[i][j] << "\t";
        }
        output << "\n";
    }
    return output;
}
int main()
{
    matrix m1(3, 3), m2(3, 3), m3(3, 3);
    std::cin >> m1;
    std::cin >> m2;
    m3 = m1 + m2;
    std::cout << m3 << std::endl;
    return 0;
}

This program is working as I expect when the destructor is not defined, but as we all know that when we allocate memory dynamically using new keyword we have to deallocate memory that is dynamically allocated.

When I define the destructor, the program returns garbage value in resultant matrix in object m3, which in our case should return addition of two matrix m1 and m2. How do I overcome this problem? Did I make a mistake while defining the destructor?

Aucun commentaire:

Enregistrer un commentaire