0

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

user243380
  • 77
  • 7
  • What is the problem? Wouldn't a plain old `delete[]` be the obvious way to go? Note however, that you should probably use a `std::vector` instead, and all your memory management troubles will simply go away. – 5gon12eder Jun 10 '15 at 18:10
  • Also be aware of the `&B == this` case (self-assignment). – 5gon12eder Jun 10 '15 at 18:11
  • yes i know the class vector, but in this exercise is no allow use vector. And dont know the way to solve this @ 5gon12eder – user243380 Jun 10 '15 at 18:13
  • You might also want to check out the [copy and swap idiom](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom) – NathanOliver Jun 10 '15 at 18:16

1 Answers1

2

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];
user4581301
  • 33,082
  • 7
  • 33
  • 54
  • @user243380 Look back in another minute or two. I forgot a vital part and am editing the answer. – user4581301 Jun 10 '15 at 18:36
  • @user243380 Updated to move reassignment of row and col to after using them to delete the old matrix. Oops. added quickie loop t copy data from Matrix B to this. – user4581301 Jun 10 '15 at 18:39