When I include i++; inside this loop I get a runtime error and I have no idea why I get it:
Do you have any idea?

while (i <= 3){
        
           if (tauler[PacMan.y][PacMan.x]==0)
               xoc = 0;
           else if (tauler[PacMan.y][PacMan.x]==1)
               xoc = 1;
           else if (tauler[PacMan.y][PacMan.x]==2)
               xoc = 2;
           else 
               xoc = 3;
               
        
         i++;
         PacMan.x += dx;
         PacMan.y += dy;
}

Dani AI

Generated

The crash was not caused by i++ itself but by the loop exposing an out‑of‑range access when the PacMan coordinates were used as indexes. confirmed the problem was an invalid grid index; that is classic undefined behavior in C/C++ and will often show up only after changing how many times or in what order the loop runs. 's hint about the initial value of i is useful for debugging, but the real fix is to guard every array access.

Practical checks and fixes:

  • Always compute and use the actual row/column limits (for example from container sizes) and test coordinates before indexing.
  • Use assertions or at() on std::vector to catch bad accesses early during development.
  • Log the values of the index variables (or print them once just before the access) so the offending coordinate and iteration count are visible.
  • If movement (dx/dy) happens each iteration, check the new position before indexing, or check the destination first and only apply the move if it stays in bounds.

Example patterns (adapt to your types/containers):

if (y >= 0 && y < rows && x >= 0 && x < cols) {
cell = tauler[y][x];
} else {
/ handle out of bounds: skip, clamp, or break /
}

Or with vectors:

cell = tauler.at(y).at(x); // throws std::out_of_range for invalid indexes

A final caution: prefer explicit boundary logic over relying on loop counters matching array size. Undefined behavior from out‑of‑bounds access is the likely culprit whenever a seemingly harmless change (like i++) makes a crash appear. For background on undefined behavior see Undefined Behavior — cppreference.

Recommended Answers

All 3 Replies

What was the value of i before you went into the while loop?

Solved,
tauler[PacMan.y + 1 ] is an invalid vaule.
Thanks to everyone who has helped.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.