简体   繁体   English

复制动态分配的2D数组

[英]Copying a dynamically allocated 2D array

I have a question as follows: 我有一个问题,如下所示:

I declared two pointer-to-pointer double-type variables **matrix1 and **matrix2 and allocate them by new operator to become 2D arrays. 我声明了两个指针对指针双型变量**matrix1**matrix2 ,并由new运算符将它们分配为2D数组。 First I used for loop to make matrix1 point to double-type data called element , then I copy matrix1 to matrix2 , which means matrix2 points to element too. 首先,我使用循环使matrix1指向称为element双类型数据,然后将matrix1复制到matrix2 ,这意味着matrix2指向element Then problem comes: I used delete operator to terminate matrix1 after copying, but then the values matrix2 point to became extremely strange. 然后问题来了:我使用delete运算符在复制后终止了matrix1 ,但是随后matrix2的值变得非常奇怪。 I think that was because after deleting matrix1 , element terminates, so I think one of a solution is let matrix2 point to other address with the values same with element. 我认为这是因为删除了matrix1element终止了,所以我认为一种解决方案是让matrix2指向其他地址,其值与element相同。 But I don't know how to do this(copy element to new dynamic memories and won't disappear after deleting matrix1 ) in an efficient way, can somebody help me? 但是我不知道如何有效地做到这一点(将元素复制到新的动态内存中,并且在删除matrix1之后不会消失),有人可以帮助我吗? thank you. 谢谢。

void MatCpy(double **InMat, double **OutMat, int NumOfRow, int NumOfCol)
{
    for (int j = 0; j < NumOfRow; j++)
    {
        for (int i = 0; i < NumOfCol; i++)
        {
            OutMat[j][i] = InMat[j][i];
        }
    }
}

double **Malloc2D_Dbl(int row, int col)
{
    double **data = new double*[row];

    for (int i = 0; i < row; i++)
        data[i] = new double[col];

    return data;    
}

void load(char *load_path, double **data, int height, int width) // function for loading
{
    int i = 0, j = 0;
    char buffer[30];
    file_handle = fopen (load_path, "r");   
    for (int k = 0; k < width*height; k++)  
    {
        fscanf (file_handle, "%s", &buffer);  
        j = k / width;
        i = k % width;                
        data[j][i] = atof(buffer);   
    }   
    fclose (file_handle);
}

Sorry I am a noob.... 抱歉,我是菜鸟。

More efficient than copying the individual elements is to use memcpy like this: 比复制单个元素更有效的方法是使用memcpy如下所示:

void MatCpy(double **InMat, double **OutMat, int NumOfRow, int NumOfCol) {
   for(int j=0; j<NumOfRow; j++) {
        memcpy(OutMat[j], InMat[j], NumOfCol*sizeof(double));
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM