r0bb077
r0bb077

Reputation: 752

Variable changing for unknown reason

I have these two methods called one after another;

m_Fence.Initialise(7);
m_Fence.CreateSquareFence();    

Here's each of their details;

void CFence::Initialise(int size)
{
    m_square_size = size;
}

void CFence::CreateSquareFence()
{
    int l_Vector_Pos = 0;

    //Set initial vector at origin and start of first fence
    CVector3f l_Fence_Position = CVector3f(0.0f,0.0f,0.0f);

    int l_side = 0; // Makes sure only 4 sides get created
    std::string bools[4] = {"plus_z", "plus_x", "minus_z", "minus_x"};
        //Draw 1st fence on 0 x-axis
        while(l_side < 4)
            {
                for(int i=0 ; i<=m_square_size ; i++)
                    {                   
                    //Find which direction it's going and set Fence position and add to vector
                    if(bools[l_side] == "plus_z" &&  i>0)
                        l_Fence_Position += CVector3f(0.0,0.0,beamLength);
                    else if(bools[l_side] == "plus_x" && i>0)
                        l_Fence_Position += CVector3f(beamLength,0.0,0.0);
                    else if(bools[l_side] == "minus_z" && i>0)
                        l_Fence_Position += CVector3f(0.0,0.0,-beamLength);
                    else if(bools[l_side] == "minus_x" && i>0)
                        l_Fence_Position += CVector3f(-beamLength,0.0,0.0);

                    fences[l_Vector_Pos].setPosition(l_Fence_Position);
                    l_Vector_Pos++;

                    //Increase this int to let it know what side we're creating
                    if(i == m_square_size) 
                        {
                            l_side++;
                    }
                }
            }
}

I pass the 7 through and it initially changes the m_square_size variable to 7 but when I call the CreateSquareFence method it ends up becoming 0 and I'm struggling to see why.

Upvotes: 1

Views: 94

Answers (1)

Turning my comment into an answer

Make sure fences is big enough so that you don't reach out of bounds and trump neighbouring mnemory (more generally, invoke Undefined Behaviour).


On a side note, that code seems way too complex. You could simplify it like this:

void CFence::CreateSquareFence()
{
  int l_Vector_Pos = 0;

  //Set initial vector at origin and start of first fence
  CVector3f l_Fence_Position = CVector3f(0.0f, 0.0f, 0.0f);

  CVector3f offsets[4] = {
    CVector3f(0.0, 0.0, beamLength),
    CVector3f(beamLength, 0.0, 0.0),
    CVector3f(0.0, 0.0, -beamLength),
    CVector3f(-beamLength, 0.0, 0.0)
  };
  for (int l_side = 0; l_side < 4; ++l_side) {
    for (int i = 0; i <= m_square_size; ++i) {
      if (i>0)
        l_Fence_Position += offsets[l_side];
      fences[l_Vector_Pos].setPosition(l_Fence_Position);
      ++l_Vector_Pos;
    }
  }
}

Upvotes: 1

Related Questions