Some problems:
1) data2 doesn't point to any of your double data ... it points to pointer_to_double values. So using memcpy with this pointer isn't going to copy any of your double data.
2) Even if data2 did point to your double data (it doesn't), the method you are using to allocate your rows of double data does not guarantee that the memory for the rows will be contiguous in memory ... in fact they could be scattered all over in memory. So attempting to copy all of the rows as one contiguous block of data using memcpy could easily seg fault.
I have never been a fan of allocating array data like you are doing. It prevents you from doing anything reliably downstream in your code that expects the data to be contiguous. It is better IMO to just allocate the entire block of memory up front to make sure it is contiguous and then to set up your row pointers accordingly if that is the syntax you really want to use in your code (which btw I am also not a fan of).
3) You didn't delete any of your new allocations (the row pointers and the row data).
4) You don't copy the correct number of bytes in this line:
memcpy((void*)mxGetPr(pArr), (void*)data2, sizeof(data2));
Remember, data2 is a pointer, not an array. So sizeof(data2) is just the size of a pointer ... it is not the size of the data that it points to. You will need to supply a manual calculation for that argument. (Side point: the conversion to pointer_to_void will happen automatically ... you don't have to explicitly cast that)
-------
E.g., I prefer something like this if you insist on the [ ][ ] syntax in your code:
double *data1 = new double[rows*columns]; // Ensures data is contiguous
double **data2 = new double*[rows];
data2[0] = data1; // Point to first row
for (int i = 1; i < rows; i++) {
data2[i] = data2[i-1] + columns; // Point to subsequent rows
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
data2[i][j] = vTest[j];
}
}
Then for the memcpy, use data1:
memcpy( mxGetPr(pArr), data1, sizeof(*data1)*rows*columns ); // Manually calculate #bytes
Then at the end you only have data2 and data1 to delete.
Best Answer