Assigning pre-allocated array to pointer in class constructor C++

65 views Asked by At

I am working on a project for my advanced CFD class, in which we have to solve the heat equation over a curvilinear mesh. I am trying to create an object which will store all of my data, to allow me to visualize it easily later on. This object is created using a class called Solution. Solution contains 8 public variables, all of which are double precision, *x, *y, *u, *v, *T, nx, ny and N, where x and y store the coordinates for each point, u and v the velocities for each point, T stores the temperature for each point, nx and ny store the number of grid points in the x and y direction, and finally N stores the total number of grid points. I have 3 constructors, the first of which initializes the object with all null pointers or values of 0.

Solution::Solution() : X(nullptr), Y(nullptr), u(nullptr), v(nullptr), T(nullptr), nx(0), ny(0), N(0) 

The second constructor takes a value for nx and ny, calculates the number of points, allocates memory for each of the arrays, and initializes their values to 0.

// Constructor to initialize solution struct with 0 values
Solution::Solution(unsigned long iNx, unsigned long iNy) : X(nullptr), Y(nullptr), u(nullptr), v(nullptr), T(nullptr), nx(iNx), ny(iNy)
{
    N = nx * ny; // Total number of grid points

    // Allocate memory for solution variables
    O.alloc1D(&X, N);
    O.alloc1D(&Y, N);
    O.alloc1D(&u, N);
    O.alloc1D(&v, N);
    O.alloc1D(&T, N);

    // Initialize variables values to 0
    for(int i = 0; i < N; i++)
    {
        X[i] = 0.0;
        Y[i] = 0.0;
        u[i] = 0.0;
        v[i] = 0.0;
        T[i] = 0.0;
    }
}

Where I am having trouble is for my 3rd constructor, in which I hope to create the object using pre-defined arrays.

// Constructor to initialize solution struct using vectors that already exist
Solution::Solution(unsigned long iNx, unsigned long iNy, double *iX, double *iY, double *iu, double *iv, double *iT) :
                   X(iX), Y(iY), u(iu), v(iv), T(iT), nx(iNx), ny(iNy)

I am having issues figuring out how to assign the arrays to these values. Looking at just X, if I try to implement an array

double x[4] = {1.0, 2.0, 3.0, 4.0};

for X in the constructor it gives me an error as it cannot assign a double to double*. If I try to write

double *x[4] = {1.0, 2.0, 3.0, 4.0};

it gives me an error as it cannot assign double to double* for each value in the array. If I try

double *x;
double x1[4] = {1, 2, 3, 4};

x = &x1;

it gives me an error because it cannot convert double(*)[4] to double in initialization. I feel like there is an easy solution to let me construct my Solution object with arrays that are already defined, but I'm getting stuck. Thank you for your help.

0

There are 0 answers