user243380
user243380

Reputation: 77

assignment operator in c++ delete memory

I'm trying to delete the memory first before allocate new memory, but i dont know how to make, and I have one problem when try to resize the matrix.

Matrix & operator=(const Matrix &B){            
            row = B.row;
            col = B.col;

            if (matrix==0){
                matrix = new int*[row];
                for (int i = 0; i < row; ++i)
                    matrix[i] = new int[col];
            }
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {                 
                    matrix[i][j] = B.matrix[i][j];
                }
            }   
        return *this;

    }

For example (resize)

Matrix matrixA(1, 1);
Matrix matrixB(2, 2);
matrixA = matrixB;

Thank you & best regards

Upvotes: 0

Views: 103

Answers (1)

user4581301
user4581301

Reputation: 33931

Use delete[] on each row then on matrix.

if (matrix!=NULL){
    for (int i = 0; i < row; ++i)
        delete[] matrix[i];
    delete[] matrix;
}
row = B.row;
col = B.col;
matrix = new int*[row];
for (int i = 0; i < row; ++i)
    matrix[i] = new int[col];

Note that this does not copy the contents of the source matrix. Need another loop for that

for (int i = 0; i < row; ++i)
    for (int j = 0; j < col; ++j)
        matrix[i][j] = B.matrix[i][j];

Upvotes: 2

Related Questions