2015-11-08 41 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; 




     } 

    }