For an assignment, I had to separate some code for Conway's Game of Life into multiple files, but now I'm trying to get a deeper understanding of why the code was written the way it was. I have a class, World
, and part of the constructor for that class looks like this:
world.h:
class World {
public:
// Constructor/destructor
World();
~World();
void updateWorld();
...
private:
char **m_grid_1;
char **m_grid_2;
...
};
world.cpp:
World::World()
{
m_toggle = true;
m_grid_1 = new char*[MAX_ROWS];
m_grid_2 = new char*[MAX_ROWS];
for (int i = 0; i < MAX_ROWS; i++) {
m_grid_1[i] = new char[MAX_COLS];
m_grid_2[i] = new char[MAX_COLS];
}
...
}
MAX_ROWS
and MAX_COLS
are globals that live in a header now.
Arrays have always kind of confused me, so these questions might seem kind of basic:
What does char** mean in the context of the member variable
m_grid_1
orm_grid_2
? Pointer to a pointer ofchar
s? Those members are 2D arrays, so I'm not sure why pointers are used here instead.Why is
new
used here in combination with that loop in the constructor? Couldn't you just saym_grid_1[MAX_ROWS][MAX_COLS];
?
Also, rather than toggle between the two grids, if I wanted to make a local copy of m_grid_1
in the member function updateWorld()
and use that local copy to get the next state of the game, would I need to use new
? This is what I have now, and it seems to work, but I'm not sure if I'm doing something wrong by not dynamically allocating the 2D array here:
void World::updateWorld() {
char grid_copy[MAX_ROWS][MAX_COLS];
for (int i = 0; i < MAX_ROWS; i++) {
for (int j = 0; j < MAX_COLS; j++) {
grid_copy[i][j] = m_grid_1[i][j];
}
}
// loop over grid_copy to find next state of m_grid_1
}