Search code examples
c++pointersargument-passingdynamic-arraysclass-constructors

How to pass a 'double*' to a class function, and apply that value to another 'double*' in that class


I am trying to pass a double* which holds an array of doubles, into the constructor of my class, and assign the value element for element.

Main:

int main()
{
    double* data = new double[4];
    data[0] = 1.1; data[1] = 2.2; data[2] = 3.3; data[3] = 4.4;

    Matrix a(2,2,data);

    return 0;
}

And this is my constructor:

Matrix::Matrix(int M, int N, double* input_data)
{
    this->M = M;
    this->N = N;

    cout << "Matrix Constructor: M: " << M << "\tN: " << N << endl;

    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            data[i*N+j] = input_data[i*N+j]; //***This is the problem***
        }
    }

}

Any attempt to index past input_data[0] in the constructor causes a crash. data[] can be accessed fine, and I can index past input_data[0] of data in my main function.

I'm assuming this should not be done this way, and would appreciate any nudge in the right direction.


Solution

  • It seems that you're not allocating memory for data in your constructor.

    Matrix::Matrix(int M, int N, double* input_data)
    {
       data = new double[M*N];
       //....
    }