0

A very good answer to how to create an Armadillo matrix around existing memory is given here: armadillo C++: matrix initialization from array.

I have a situation however where I would like to create an Armadillo matrix from a const array, without copying the data first. The first part is easy:

  • mat(const aux_mem*, n_rows, n_cols)

Create a matrix by copying data from read-only auxiliary memory.

However this copies the memory first, which would be unnecessary in my case.

I would like to have something like this:

const double* ptr = start; // I cannot modify the source of this pointer

const amra::mat M(ptr, 4, 4, /*copy*/ false, /*strict*/ true); 

However this exact constructor does not exist. Is there an alternative method that I'm missing?

Roberto
  • 958
  • 13
  • 33

1 Answers1

1

Use const_cast to remove the const qualifier from the pointer.

In your case this is const arma::mat M(const_cast<double*>(ptr), 4, 4, false, true);

mtall
  • 3,574
  • 15
  • 23
  • I had no idea it was possible to cast a const pointer back into a non-const pointer. I thought const pointer was a solid protection, but I guess it still remains up to the developer to respect it. – Roberto Feb 10 '20 at 14:53
  • 1
    While this is the correct answer, usually it is considered bad practice to cast const away (https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es50-dont-cast-away-const). You should at least make the arma::mat that you create this way also const to avoid allowing it to modify memory that should not be modified. – darcamo Feb 11 '20 at 21:15