2013-04-22 16 views
0

我有這樣的聲明,在我cc.hç頂點數組錯誤的價值觀

Vertex *graphVertices2; 

typedef struct 
{ 
    float XYZW[4]; 
    float RGBA[4]; 
} Vertex; 

而在我cc.ci請執行以下操作:

float vert [] = {306, 319, 360, 357, 375, 374, 387, 391, 391, 70, 82, 94, 91, 108, 114, 125, 127, 131}; 
      graphVertices2 = transformIntoVertex(vert, 18); 

Vertex *transformIntoVertex(float *v, int size){ 
    int i; 
    float x_axis = x_0 + (x_Max/size); 
    Vertex graphVertices[18]; 

    for(i = 0; i < size; ++i){  
     graphVertices[i].XYZW[0] = x_axis; // x 
     graphVertices[i].XYZW[1] = v[i]; // y 
     graphVertices[i].XYZW[2] = 0.0f; // z 
     graphVertices[i].XYZW[3] = 1.0f; // w 
     if(size <= 9){ 
     graphVertices[i].RGBA[0] = 1.0f; 
     graphVertices[i].RGBA[1] = 0.0f; // g 
     graphVertices[i].RGBA[2] = 0.0f; // b 
     graphVertices[i].RGBA[3] = 0.0f; // a 
     }else{ 
      graphVertices[i].RGBA[0] = 0.0f; // r 
      graphVertices[i].RGBA[1] = 1.0f; // g 
      graphVertices[i].RGBA[2] = 0.0f; // b 
      graphVertices[i].RGBA[3] = 0.0f; // a 
     } 
     x_axis = x_axis + x_axis; 
     return graphVertices; 
    } 

但是當我打印我得到錯誤的價值觀graphVertices2。問題不是來自我認爲的函數,我已經打印了for循環,並且所有內容都有正確的值。這些值在頂點中間開始變得奇怪。我無法弄清楚爲什麼。

此行是做正確的歸因:

graphVertices[i].XYZW[1] = v[i]; 

我已經打印了和檢查。但是在頂點的中間,值變得非常大。

+0

您正在返回一個本地範圍變量地址,該地址在您離開'transformIntoVertex()'後不再有效。要麼動態分配返回內存,要麼使用本地'static',要麼使用全局。哦,*不*使用全球= P – WhozCraig 2013-04-22 17:38:06

回答

2

的問題不是來自我覺得功能,

它。

Vertex graphVertices[18]; 
// ... 
// do stuff 
// ... 
return graphVertices; 

您正在返回一個自動數組 - 它將在函數返回時超出範圍。你的程序調用未定義的行爲,所以任何事情都可能發生。解決這個問題的通常建議是:使其成爲static(並且讀取關鍵字的作用),或者malloc()爲它提供一些動態內存(在這種情況下,您在使用後還將不得不使用free())。

+0

好吧。所以你的意思是,當我在函數內部創建一個新的頂點數組時,我應該使用malloc,以便在函數調用之後不會銷燬爲該臨時數組保留的內存? – 2013-04-22 17:49:27

+0

@JohnHarrod準確無誤。 – 2013-04-22 17:50:04