Home > Software engineering >  C : Copy the vector of pointers to arrays, to Eigen::ArrayXd
C : Copy the vector of pointers to arrays, to Eigen::ArrayXd

Time:11-17

I have std::vector<double *> x, in which each elements points to C-style double array. The values of double arrays are changing with each iteration of my program. I would like to create a copy of them into Eigen::ArrayXd x_old so I can compute a difference with new values. I have tried to use Eigen::Map but it copied only one array and they were still connected memory-wise, so it was not a copy technically. Now I tried to memcpy it, but I am getting only the first array. Thank you for your help

std::vector<double *> x;
x.push_back( new double[2]{1, 2} );
x.push_back( new double[2]{3, 4} );

Eigen::ArrayXd x_old(4);
memcpy(x_old.data(), *x.data(), 4*sizeof(double));

CodePudding user response:

The problem with memcpy(x_old.data(), *x.data(), 4*sizeof(double)); is that since you manually allocated memory for each elements of the vector, the data underneath aren't contiguous anymore, ie 2 is not followed by 3.(The locations of the pointers are contiguous, but the arrays they are pointing to are not)

So when you put them into x_old, you can't get them as a contiguous memory. Instead you need to add each elements of the vector separately:

memcpy(x_old.data(), x[0], 2 * sizeof(double));
memcpy(x_old.data()   2, x[1], 2 * sizeof(double));

Or write a for-loop:

for(std::size_t s = 0; const auto& data: x)
{
    memcpy(x_old.data()   s, data, 2 * sizeof(double));
    s  = 2;
}

Sidenote, *x.data() is the same as saying x[0].

  • Related