2015-11-08 42 views
0

您好我正在使用QT到我的工作,我不能从内存中删除一个2D浮点数组。
我正在处理图像,所以我需要删除数组,以免消耗太多内存。
我试图这样但不工作:我如何删除浮动二维数组在c + +中,与QT

int n = test.cols; // number of colums image. 
int m = test.rows; // number of lines image 
float soma[test.cols][test.rows]; // create a array 2D for operations... 

for(int i = 0 ; i < n + 2 ; ++i) 
{ 
for(int j = 0 ; j < m + 2 ; ++j) delete[] soma[i][j] ; 
delete[] soma[i]; 
} 
delete[] soma; 
+0

您是否可以使用发布的代码编译和构建程序? –

回答

0

在这种特定的情况下数组是无论是在堆栈或在存储器中的数据部分,而不是堆。只有HEAP中分配有new []的存储器才能被delete []运算符删除。

不是这个例子创建了一系列不连续的行遍布内存。

如果您像这样分配内存。

float ** soma = new float* [test.rows]; 
// WARNING UNITIALIZED CONTENT 
for(int i = 0 ; i < test.rows; ++i) soma[i] = new float[test.cols]; 

然后,您可以删除这样

for(int i = 0 ; i < test.rows; ++i) delete [] soma[i]; 
delete [] soma; 

内存然而它往往是更好地分配一个单一的连续图像(如尺寸不是太大)。然后使用第二个数组将行偏移记录为指针。

// WARNING UNITIALIZED CONTENT 
float * buffer = new float [ test.rows * test.cols ] 
float ** soma = new float* [ test.rows ]; 
for(int i = 0 ; i < m; ++i) soma[i] = soma + i * test.cols; 

然后将其删除这样

delete [] soma; 
delete [] buffer; 

或者只是使用std ::向量。

0

Thx,我使用std :: vector,我正在处理图像,静态分配不是一个好方法,所以我使用std :: vector,为这项工作,感谢您的关注,请按照我的代码现在:

vector <float> lines(test.rows); 
    vector<vector<float> > colums(test.cols,lines); 



    for(int i=0;i<colums.size(); i++) { 
     for (int j=0;j<colums[i].size(); j++){ 


      colums[i][j] = ((float)imagem.at<Vec3b>(j,i)[0]/(float)(imagem.at<Vec3b>(j,i)[0] + (float)imagem.at<Vec3b>(j,i) [1] + (float)imagem.at<Vec3b>(j,i) [2]))*255; 
      aux  = (int) floor(colums[i][j] + 0.5); 
      colums[i][j] = aux; 
      test.at<Vec3b>(j, i)[0] = aux; 
      aux = 0; 




       colums[i][j] = ((float)imagem.at<Vec3b>(j,i)[1]/ 
           (float)(imagem.at<Vec3b>(j,i)[0] + 
           (float)imagem.at<Vec3b>(j,i) [1] + 
           (float)imagem.at<Vec3b>(j,i) [2]))*255; 

       aux  = (int) floor(colums[i][j] + 0.5); 
       colums[i][j] = aux; 
       test.at<Vec3b>(j, i)[1] = aux; 
       aux = 0; 


          colums[i][j] = ((float)imagem.at<Vec3b>(j,i)[2]/ 
              (float)(imagem.at<Vec3b>(j,i)[0] + 
              (float)imagem.at<Vec3b>(j,i) [1] + 
              (float)imagem.at<Vec3b>(j,i) [2]))*255; 

          aux  = (int) floor(colums[i][j] + 0.5); 
          colums[i][j] = aux; 
          test.at<Vec3b>(j, i)[2] = aux; 
          aux = 0; 




     } 

    }