0

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.

4
  • I think perhaps (x-1)/3 is giving a floating point number instead of an integer. Try using ceil((x-1)/3) or (x-1)/3 >> 0 Commented Dec 21, 2013 at 20:03
  • 2
    Typo? You say y coord but you typed terrainzPos. Commented Dec 21, 2013 at 20:03
  • @KumarHarsh No, it doesn't do floating point arithmetic: x is an int, and the C dialects won't convert any integers to floats unless one of the operands is a float. Commented Dec 21, 2013 at 20:35
  • @cmaster oh dear lord... yes ofcourse, you're right! too much JS has killed my C :( Commented Dec 22, 2013 at 6:04

1 Answer 1

1

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];
}
Sign up to request clarification or add additional context in comments.

3 Comments

what do you mean by resize() them 'properly'?
@DavidGraovac: Resize them to be large enough hold all of the plainVerts. BTW, I just noticed what's likely the real problem: sizeof. I think you likely mean desert_scene_plainVerts.size() if it's a vector, or sizeof(desert_scene_plainVerts) / sizeof(desert_scene_plainVerts[0]) if it's an array.
@DavidGraovac: You need to resize it before the loop. ie. terrainxPos.resize( desert_scene_plainverts.size() / 3 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.