David Graovac
David Graovac

Reputation: 43

Splitting Array in C++

I'm making a game and I have an array of floats that make a 3D models that I've placed in with opengl. What I want to do is separate the x,y&z coords and make them into a multi-dimensional array. I want to do this so I can adjust the y position in relation to the terrain. The for loop that I have placed in my init function is as follows:

    for (int x = 0; x < sizeof(desert_scene_plainVerts); x++) {
    if (((x + 3)%3) == 0) {
        //x coord
        terrainxPos[x/3] = desert_scene_plainVerts[x];
    }
    else if (((x + 1)%3) == 0) {
        //z coord
        terrainzPos[(x-2)/3] = desert_scene_plainVerts[x];
    }
    else{
        //y coord
        terrainzPos[(x-1)/3] = desert_scene_plainVerts[x];
    }
}

I am getting an error on this line:

terrainzPos[(x-1)/3] = desert_scene_plainVerts[x];

The error goes as follows:

Thread 1: EXC_BAD_ACCESS (code=2, address= 0x10 etc.)

Does anybody know what I am doing wrong.

Upvotes: 0

Views: 109

Answers (1)

Joe Z
Joe Z

Reputation: 17936

Your logic looks ok, assuming you've declared terrainxPos[], terrainyPos[] and terrainzPos[] correctly. If those are vectors, then make sure you resize() them properly.

However, your loop may be clearer and easier to reason about written like this:

for (int x = 0, v = 0; x < sizeof(desert_scene_plainVerts); x += 3, v++) {
    terrainxPos[v] = desert_scene_plainVerts[x + 0];
    terrainyPos[v] = desert_scene_plainVerts[x + 1];
    terrainzPos[v] = desert_scene_plainVerts[x + 2];
}

Upvotes: 1

Related Questions