0

I am trying to assign an object to an array position. The position is given by an static variable (int) that contains the number of elements of the array. The size of tEntities is 5 and the size of fFuncionesList is 4, so it´s not a size problem.

if (TEntity::uEntityCount < 5)
        {
            iRandFuncList = rand() % (3 + 1);
            iRandPosX = rand() % (120 + 1);
            iRandPosY = rand() % (30 + 1);
            tEntities[TEntity::uEntityCount] = new TEntity((fFuncionesList[iRandFuncList]), iRandPosX, iRandPosY);
        }

TEntity(funcEntity *funcs, int x, int y)
    {
        m_ix = x;
        m_iy = y;
        m_funcs = funcs;
        uEntityCount++;
    }

Error Debuger

I have tried to assign the value of the static variable to an int variable and it works, I would like to understand why it doesn't work with the static variable.

if (TEntity::uEntityCount < 5)
            {
                iRandFuncList = rand() % (3 + 1);
                iRandPosX = rand() % (120 + 1);
                iRandPosY = rand() % (30 + 1);
                int pos = TEntity::uEntityCount;
                tEntities[pos] = new TEntity((fFuncionesList[iRandFuncList]), iRandPosX, iRandPosY);
            }

Thank you in advance.

10
  • What is the size of fFuncionesList? Commented Nov 17, 2019 at 10:04
  • @goodvibration 4 Commented Nov 17, 2019 at 10:05
  • How does it fail? Do you get a compilation error, a runtime error of a weird output? Commented Nov 17, 2019 at 10:06
  • I have tried to assign the value of the static variable to an int variable and it works, I would like to understand why it doesn't work with the static variable. - implies that your program's behavior is undefined, and adding another variable on the stak has changed its behavior (and coincidentally made it do what you wanted). Commented Nov 17, 2019 at 10:06
  • 1
    If tEntities is size 4, then do the math. Look at the picture you posted. Which slot are you indexing? Hint: tEntities[4] is the fifth element. Regardless, without a minimal reproducible example its all guesswork anyway. Best of luck. Commented Nov 17, 2019 at 10:58

1 Answer 1

2

Your problem comes when you call constructor

tEntities[TEntity::uEntityCount] = new TEntity((fFuncionesList[iRandFuncList]),...);

it increment the uEntityCount

uEntityCount++;

then you assign the object pointer to tEntities[TEntity::uEntityCount] it will be placed at the next position so if current uEntityCount=4 it will place the pointer at uEntityCount=5 which is outside you array

Sign up to request clarification or add additional context in comments.

Comments

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.