-3

I would like to copy the 2 matrices. With a copy element by element through 2 for loops (row and column), after several mathematical operations and copies the final result is correct while using "memcpy" the final result is wrong in the decimal places. The code is as follows.

double **L_original;
double **L;
int nF,nU;



 L = new double*[nU]();
 L_original = new double*[nU]();
  for(int i=0; i<nU; i++){
      L_original[i] = new double[nF]();
      L[i] = new double[nF]();
  }

// copy element to element
/*for(int i=0; i<nU; i++)
        for(int j=0; j<nF; j++)
            L[i][j] = L_original[i][j];*/

memcpy(L, L_original, sizeof(L_original));

This is the correct result:Matrix Correct This is the output: output when using memcpy

273K
  • 29,503
  • 10
  • 41
  • 64
Snake91
  • 21
  • 1
  • 4
  • 1
    `sizeof(L_original)` is `sizeof(double**)` and therefore independent of `nU` – UnholySheep Apr 14 '20 at 16:46
  • Please, consider implementing an actual matrix class (see e.g. [this](https://stackoverflow.com/a/2076668/4944425)), instead of tempting fate with a double pointer. – Bob__ Apr 14 '20 at 16:59
  • Heads up: you are not writing C++, you are writing C. In C++, we would simply write `auto L_original = vector>{{0.0, 1.0}, {2.0, 3.0}}; auto L = L_original;` which achieves a deep copy with a single step. – alter_igel Apr 14 '20 at 17:00
  • 1
    Implementing your 2d array [this way](https://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048), then it is simply `memcpy(L, L_original, sizeof(double)*nU*nF);`. – PaulMcKenzie Apr 14 '20 at 17:07

1 Answers1

2

your L and L_original are 2D matrices, made of an array of pointers to separately allocated 1D vectors. These memory addresses may not be in a contiguous memory space. So you can't use a single memcpy to copy all subvectors.

you will have to use a for loop to apply memcpy between each L[i] and L_original[i].

also, your sizeof() operator is used incorrectly. what you need to copy is the byte length of the data (of the 1D subvector), not the length of the pointer. You need something like

  for(int i=0; i<nU; i++)
     memcpy(L[i],L_original[i], sizeof(double)*nF);
FangQ
  • 1,444
  • 10
  • 18