Jirikai Naito
Jirikai Naito

Reputation: 5

C++ Pointer to an array of enum

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
}

Upvotes: 0

Views: 401

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

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.

Upvotes: 3

Related Questions