Xalion Xalion - 10 days ago 6
C++ Question

C++ fill dynamic array int

I am writing program which will multiply matrix using threads. I have problem with filling dynamic int array (cannot use vector).

cpp file:

Matrix::Matrix(int n, int m)
{
mac_ = new int[n * m];
}

Matrix::Matrix(std::istream & is)
{
int tmp;
int i = 0;
is >> m_; //rows
is >> n_; //columns

Matrix(n_, m_); // using 1st constructor

while (is.peek() != EOF) {
is >> tmp;
mac_[i] = tmp; // debug stop here
i++;
}
}


part of hpp file:

private:
int n_; // columns
int m_; // rows
int *mac_;


From debug I get:


this 0x0079f7b0 {n_=3 m_=2 mac_=0x00000000 {???} }


I know that i can write
mac_ = new int(n_*m_);
in 2nd constructor but I want to know why 1st does not work.

Answer
// ...

Matrix(n_, m_); // using 1st constructor

while (is.peek() != EOF) {
    is >> tmp;
    mac_[i] = tmp; // debug stop here
    i++;
}

Looks like you think calling the constructor here constructs the actual object (this), and then you access its member attribute mac_.

In fact, calling the constructor as you did creates an other object unrelated to this matrix (since you're not storing it in variable, it is destructed at the end of the line).

So because you constructed an other object instead of this, this->mac_ is uninitialized, thus your bug.

Modify your code like this:

Matrix::Matrix(int n, int m)
{
    init(n, m);
}

Matrix::Matrix(std::istream & is)
{
    int tmp;
    int i = 0;  
    is >> m_; //rows
    is >> n_; //columns

    init(n_, m_);

    while (is.peek() != EOF) {
        is >> tmp;
        mac_[i] = tmp; // debug should not stop here anymore
        i++;
    }
}

void Matrix::init(int n, int m)
{
    mac_ = new int[n * m];
}

Note: here I take out the inititialization in a function init (should probably be a private method) to avoid code duplication.