0

I've got a problem with trying to point to a vector and then setting the value of an element when trying to de-reference it.

std::vector < Maze::TILE_CONTENT> * theGrid;
if (go->team == GameObject::GT_BLUE)
    *theGrid = m_myGridBlue;
else
    *theGrid = m_myGridRed;

if (go->curr.y < m_noGrid - 1)
{
    theGrid[next.y * m_noGrid + next.x] = Maze::TILE_EMPTY; //no operate '=' matches these operands
}
1
  • When you work with pointers you need to understand what you are doing, You seem just tried to fix compile error mechanical way. Commented Jan 25, 2020 at 17:14

1 Answer 1

3

There are two problems here. The first is in the assignment to *theGrid. This code will copy the source vector to whatever theGrid points to. Since that pointer is uninitialized, you have Undefined Behavior, a crash if you're lucky. I think what you're trying to do is

theGrid = &m_myGridBlue;

The second problem, which gives your compilier error, is how you access the pointed-to vector. Since theGrid is a pointer to a vector, you need to dereference that pointer first:

(*theGrid)[next.y * m_noGrid + next.x] = ...;

As an alternative to the pointer, you can use a reference

std::vector<Maze::TILE_CONTENT> &theGrid = go->team == GameObject::GT_BLUE ? m_myGridBlue : m_myGridRed;

then you can access the contents of theGrid as you already are.

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

1 Comment

Or auto &theGrid = ... would be even simpler

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.