I'm trying to target a variable that is not declared in my scope. I think this should be realized by pointers. But somehow i can't get it to work properly.
I have a Grid of Points and a Walker. The Walker can go from Point to Point, but to do that, he needs to know on wich grid he is. In my first attempt I allways told him on wich grid he is, when i told him to go somewhere. GoTo(&grid, goal);
This didn't look so nice. So now I want to store the pointer to the Grid inside the Walker. So I only need to tell him the Grid on creation.
class CWalker {
private:
enum { POINT_FREE = 0, POINT_BLOCKED = 1, POINT_WALKED = 2 };
public:
CWalker();
CWalker(CGridXP *g, int pos);
CGridXP **grid;
int position;
void Reset();
void GoTo(int goal);
};
CWalker::CWalker(CGridXP *g,int p) {
grid = &g;
position = p;
}
void CWalker::Reset() {
for(int i = 0; i < grid->getSize(); i++) {
if (i == position) grid->setPointType(i, POINT_WALKED);
elseif (!(grid->getPointType(i) == POINT_BLOCKED)) grid->setPointType(i, POINT_FREE);
}
}
This looks right doesn't it? Well g++ doesn't think so:
1 2 3
System/CWalker.cpp:11:30: error: request for member ‘getSize’ in ‘*((CWalker*)this)->CWalker::grid’,
which is of pointer type ‘CGridXP*’ (maybe you meant to use ‘->’ ?)
for(int i = 0; i < grid->getSize(); i++) {
this message references to line 22 of the code I quoted above.
I really don't know what to do with this. Maybe I want to use '->'? I'm allready using that, wtf?
(*grid)->getSize(); ← operator precendence
Also you can use (**grid).getSize();
Or obscure. grid[0]->getSize(); and grid[0][0].getSize();
Or you can throw out double pointer. Why do you need it? It is error prone and should be avoided unless absolutely nessesary.
To illustrate: you had a bug in your code, which leads to value of your pointer to be overwritten. So your program will not work (reliably)
EDIT: took too long to write answer. Now it looks better.