2013-04-22 62 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