I assigned an array with new, but the last value of the array cannot be entered.

Asked 1 years ago, Updated 1 years ago, 114 views

#include <iostream> 
using namespace std ; 
class Matrix { 
        int** values;
        int row, column;
    public: Matrix(int row = 0, int column = 0) { this->row = row; this->column = column ; } 
    Matrix operator + (const Matrix &c) { return Matrix(row + c.row, column + c.column) ; }
    Matrix operator * (const double val) { return Matrix(row * val, column * val) ; } 
    friend ostream& operator << (ostream& os, const Matrix& c) ;
    friend istream& operator >> (istream& os, Matrix& c) ;
    } ; 
    ostream& operator << (ostream& os, const Matrix& c) { 
        for(int i = 0; i < c.row; i++){
            for(int j = 0; j < c.column; j++){
                os << **(c.values) << '\t';
            }
            os << endl;
        }
        return os ; 
    }
    istream& operator >> (istream& is, Matrix& c) { 
        int** value = NULL;
        value = new int*[c.row];
        for(int i = 0; i < c.row; i++){
            *(value) = new int[c.column];
        }
        for(int i = 0; i < c.row; i++){
            for(int j = 0; j < c.column; j++){
                cin >> value[i][j];
            }
        }
        c.values = value;
    }////////////help me crying  

int main() { 
    Matrix m1(2, 2), m2(2, 2) ; 
    cin >> m1 ; 
    cin >> m2 ;
    Matrix m3 = m1 + m2 ; 
    Matrix m4 = m3 * 10 ;
    cout << m3 << endl ; 
    cout << m4 << endl ;
}

The compilation works well, but... I put cout in the value[i][j] part and checked, but up to 1.1, 1.2, and 2.1, it's fine It suddenly stopped at 2.2. What's the cause? Did I add the wrong new?

new array operator overloading

2022-09-21 19:23

1 Answers

for(int i = 0; i < c.row; i++){
    *(value) = new int[c.column];
}

According to i, value+0 and value+1 should be accessed, respectively.

Now value+0 stores two dynamically assigned one-dimensional arrays, and the first saved one-dimensional array leaks memory.


2022-09-21 19:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.