在C ++中修改双指针而不丢失信息

问题描述 投票:0回答:1

我在C ++中声明了一个矩阵:double **matrix;

现在,我想遍历它,并使用任何以i,j坐标为参数的函数来修改其持有的值,例如,如果它是10x10矩阵,我会这样做:

for(int i = 0; i < 10; i++){
   for (int j = 0; j < 10; j++){
      matrix[i][j] = some_special_function(i,j) * matrix[i][j];
   }
} 

现在我在编译时遇到内存问题,所以我认为我需要分配一些内存,但是如果我在循环中这样做:

for(int i = 0; i < 10; i++){
   matrix[i] = new double[10];
   for (int j = 0; j < 10; j++){
      matrix[i][j] = some_special_function(i,j) * matrix[i][j];
   }
} 

与此有关的问题是我丢失了有关matrix的信息,但仍无法编译。

所以我不知道该怎么办?

c++ pointers memory-management
1个回答
0
投票
void function(double** matrix,int sze)

{
    //Copying the matrix to a temp one 
    //You need this because if you change some element in your matrix, you
    //won't be able to use it again 
    double** tempMatrix = new double*[sze];

    for(int i=0; i<sze; i++)
    {

        tempMatrix[i]=new double [sze];
        for(int j = 0; j<sze; j++)
        {
            tempMatrix[i][j] = matrix[i][j];
        }
    }


    //Now use your code
    for(int i = 0; i < 10; i++){
        for (int j = 0; j < 10; j++){
            matrix[i][j] = some_special_function(i,j) * tempMatrix[i][j];
        }
    }
    //Deleting the dynamically allocated tempMatrix
    for(int i=0; i<sze; i++)
    {
            delete[] tempMatrix[i];
    }
    delete[] tempMatrix;
    tempMatrix=nullptr;

}
© www.soinside.com 2019 - 2024. All rights reserved.