I am using a library that returns the image as a big 2D array int**
. I need to convert it into int*
1D array. I think I've managed to do it quite fast by copying memory blocks:
// have int labels** as 2D array, also have rows and cols
//create 1D array
int *labels1D = new int[rows*cols];
//copy contents
for(int i = 0; i < rows; i++) {
// Here I don't know anything about how those arrays were allocated
// Maybe std::copy would handle it for me?
std::copy_n(labels[i], cols, labels1D + i*cols);
}
So the first question is whether I can do something better here? Is everything safe here assuming that library is a black box?
I do not want much to modify the library code, but I've found additionally how the source array in my side library this->currentLabels
was created:
int** currentLabels; //in class declaration
...
// in the code
this->currentLabels = new int*[this->height];
for (int i = 0; i < this->height; ++i) {
this->currentLabels[i] = new int[this->width];
for (int j = 0; j < this->width; ++j) {
// some code for setting the value
}
}
Looks like the values for rows and cols are known.
So the second question is: can I modify this code to make it allocate the 2D array in one memory block:
this->currentLabels = malloc(nrows*sizeof(int*) + (nrows*(ncolumns*sizeof(int)));
to allow me then just map it somehow to my 1D array without copying memory?
EDIT: Thanks to @SamVarshavchik , the mapping seems to be working in the following way:
// Allocate 2-D array as one block:
// Allocate pointers:
int** labels = new int*[rows];
// Allocate data:
auto ptr=new int[rows*cols];
for(int i = 0; i < rows; i++) {
labels[i] = &ptr[i*cols];
}
// fill with values ranging 0 to certain number
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
// the code for setting the values
labels[i][j] = i+j;
}
}
// have int labels** as 2D array, also have rows and cols
//create 1D array
int *labels1D; // = new int[rows*cols];
//assign contents:
labels1D = &labels[0][0];
The right way to destroy it in the library code seems to be
delete[] ptr; //user2079303 fixed
delete[] labels;