Question

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.

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top