2017-06-16 195 views
1

我通過函數MontaVetorVerticalOtimizado(x, y, Vetor)的參數發送數組int Vetor[33];,在該數組填充之後,問題是在填充數組之後,函數OtimizaVerticalDentina()的所有變量都用值數組,這似乎令人困惑,所以我加的圖像,同時調試使其更容易理解:變量的值根據向量值而變化

第一功能

void OtimizaVerticalDentina() { 
    int Vetor[33]; 
    int x, y; 
    for (x = 1; x < NewImage.SizeX() - 1; x++) 
    { 
     for (y = 10; y < NewImage.SizeY() - 10; y++) 
     { 
      MontaVetorVerticalOtimizado(x, y, Vetor); 
      VerificaIntensidadeVetorVerticalOtimizado(Vetor); 
      if (bPreenche) { 
       NewImage.DrawPixel(x, y, 255, 255, 255); 
      } else { 
       NewImage.DrawPixel(x, y, 0, 0, 0); 
       bPreenche = true; 
      } 
     } 

    } 
} 

二級功能

void MontaVetorVerticalOtimizado(int Px, int Py, int Vetor[33]) 
{ 
    int x, y; 
    int i = 0; 
    unsigned char r, g, b; 
    for(x = Px - 1; x <= Px + 1; x++) 
    { 
     for(y = Py - 10; y <= Py + 10; y++) 
     { 
      NewImage.ReadPixel(x, y, r, g, b); 
      Vetor[i] = r; 
      i++; 
     } 
    } 
} 

注:

ImageClass NewImage; // global 

之前填充所述數組變量與它們的正常值 enter image description here

填充陣列之後的變量是與另一值(值,該值被添加到載體中)enter image description here

*我在第一個測試方法中創建了其他變量,它們也發生了變化,有沒有人知道可能發生了什麼?

+0

哪個編譯器?你是否添加了打印語句來確認(以防調試器對你說謊)? – Borgleader

+0

啊,我的眼睛,太白了! – Stargateur

+0

@Borgleader GNU GCC編譯器,我在填充數組之前和之後在控制檯上輸出變量的值,並顯示編譯器沒有說謊。 –

回答

1

我能找到的唯一解釋是你有一個緩衝區溢出。那就是你正在寫這個數組(Vetor),這個數組不夠大,而且恰好覆蓋了這個進程中不相關的內存。在這種情況下,您將覆蓋調用函數的變量xy的值。

我演示here

#include <iostream> 

void bar(int* arr) 
{ 
    for (int i = 0; i <= 35; i++) arr[i] = 255; 
} 

void foo() 
{ 
    int arr[33]; 
    int x; 
    for (x = 0; x < 5; x++) 
    { 
     std::cout << x << '\n'; 
     bar(arr); 
     std::cout << x << '\n'; 
    } 
} 

int main() 
{ 
    foo(); 
    return 0; 
} 

這將產生:0 255,並立即終止,因爲循環變量得到了覆蓋,隨後x < 5檢查失敗。你必須增加數組的大小(如果結果太小),或者確保你在其範圍內索引。