I’m creating a program containing Cells, and for that I have a Cell class and a CellManager class. The cells are organized in a two dimensional array, and the Cell class manager has two int member variables, xgrid and ygrid that reflect the size of the array.
For some reason I just cannot figure out, these member variables change during the course of program execution. Can anyone see why this is happening, or maybe point me in a direction of where to look.
The classes and functions used look like this:
class Cell
{
public:
Cell(int x, int y);
}
---------------------------------
class CellManager
{
public:
CellManager(int xg, int yg)
void registercell(Cell* cell, int x, int y);
int getxgrid() {return xgrid;}
int getygrid() {return ygrid;}
private:
int xgrid;
int ygrid;
Cell *cells[40][25];
}
-----------------------
and CellManagers functions:
CellManager::CellManager(int xg, int yg)
{
CellManager::xgrid = xg;
CellManager::ygrid = yg;
}
void CellManager::registercell(Cell *cell, int x, int y)
{
cells[x][y] = cell;
}
and here is the main function:
int main ()
{
const int XGRID = 40;
const int YGRID = 25;
CellManager *CellsMgr = new CellManager(XGRID, YGRID);
std::cout << CellsMgr->getxgrid() << std::endl; // PRINTS 40
std::cout << CellsMgr->getygrid() << std::endl; // PRINTS 25
//create the cells and register them with CellManager
for(int i = 1; i <= XGRID; i++) {
for(int j = 1; j <= YGRID; j++) {
Cell* cell = new Cell(i, j);
CellsMgr->registercell(cell, i, j);
}
}
std::cout << CellsMgr->getxgrid() << std::endl; // PRINTS A RANDOM LARGE INT, EX. 7763680 !!
std::cout << CellsMgr->getygrid() << std::endl; // PRINTS 1, ALWAYS !!
So, I initialize a CellMgr, and set xgrid and ygrid through the constructor. Then I create a bunch of Cells and register them with the CellMgr. After this, the two member variables of CellMgr have changed, anyone know how this can happen?
Arrays are zero-indexed, but you’re using them as if they are indexed from 1. As a result, your array indexing will be overwriting cells, and writing off the end of the array, which is undefined behaviour. Overwriting random other variables is certainly possible.