0

I have this declarations in my cc.h

Vertex *graphVertices2;

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

And in my cc.c i do the following:

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;
    }

But I am getting wrong values when I print graphVertices2. The problem doesn't come from the function I think, I have printed the for loop and everything is with the right values. The values start to get weird at the middle of the vertex. I can't figure it out why.

This line is doing the right attributions:

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

I have printed it and checked. But at the middle of the vertex, the values get hugely big.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Nick Spot
  • 257
  • 2
  • 4
  • 12
  • You're returning a local scope variable address, which is no longer valid once you leave `transformIntoVertex()`. Either dynamically allocate the return memory, use a local `static`, or use a global. Oh, and *don't* use a global =P – WhozCraig Apr 22 '13 at 17:38

1 Answers1

2

The problem doesn't come from the function I think,

It does.

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

You're returning an automatic array - which will be out of scope the moment the function returns. Your program invokes undefined behavior, so anything can happen. The usual advice for solving this: make it static (and the read what that keyword does), or malloc()ate some dynamic memory for it (in which case you will also have to free() it after use).

BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • Ok. So don you mean, when i create a new Vertex array inside the function, i should use malloc so that the memory reserved for that temporary array is not destroyed after function call? – Nick Spot Apr 22 '13 at 17:49