I've been struggling to understand how to work with pointers generally. I have in the example below a little sketch of an update function (updateGrid) for Game of life. The idea is to update the state of all cells in the grid between true and false (as you might know). However, I'm supposed to use pointers in order to alternate between the 'previous' and 'new' state of the grid. But I don't seem to figure out how to implement this concept of alternating pointers without making a copy of the current cells grid. Any idea?
By the way, my code below works so far just fine.
// ---------- Global Variables ----------
bool cells[MAX_SIZE][MAX_SIZE];
bool cells_next[MAX_SIZE][MAX_SIZE];
bool (*ptr)[MAX_SIZE][MAX_SIZE];
bool (*ptr_next)[MAX_SIZE][MAX_SIZE];
ptr = &cells;
ptr_next = &cells_next;
// ---------- update state ----------
void updateState() {
for (int row = 0; row < MAX_SIZE; row) {
for (int col = 0; col < MAX_SIZE; col) {
if (((*ptr)[row][col]) == 1) {
if ((numAliveNeighbors(row, col) < 2)
|| (numAliveNeighbors(row, col) > 3)) {
(*ptr_next)[row][col] = 0;
} else {
(*ptr_next)[row][col] = 1;
}
} else if (((*ptr)[row][col]) == 0) {
if (numAliveNeighbors(row, col) == 3) {
(*ptr_next)[row][col] = 1;
} else {
(*ptr_next)[row][col] = 0;
}
}
}
}
for (int row = 0; row < MAX_SIZE; row) {
for (int col = 0; col < MAX_SIZE; col) {
(*ptr)[row][col] = (*ptr_next)[row][col];
(*ptr_next)[row][col] = 0;
}
}
PS: My problem explanation may seem a little bumpy so don't hesitate for further infos.
Many thanks in advance :)
CodePudding user response:
Note these remarks:
You should use pointer to rows instead of pointers to 2D arrays.
You can alternate the pointers by swapping the via a temporary variable.
The code implements John Conway's famous Game of Life generations. ptr
points to the current board and ptr_next
points to the next generation. update()
computes the new board applying the rules for cell death and birth. When the new board has been fully updated, the pointers are swapped, so ptr
now points to the new board. This is faster than copying the full board from cells_next
to cells
.
Here is a modified version:
// ---------- Global Variables ----------
bool cells[MAX_SIZE][MAX_SIZE];
bool cells_next[MAX_SIZE][MAX_SIZE];
bool (*ptr)[MAX_SIZE] = cells;
bool (*ptr_next)[MAX_SIZE] = cells_next;
// ---------- update state ----------
void updateState() {
for (int row = 0; row < MAX_SIZE; row) {
for (int col = 0; col < MAX_SIZE; col) {
if (ptr[row][col]) {
if ((numAliveNeighbors(row, col) < 2)
|| (numAliveNeighbors(row, col) > 3)) {
ptr_next[row][col] = 0;
} else {
ptr_next[row][col] = 1;
}
} else {
if (numAliveNeighbors(row, col) == 3) {
ptr_next[row][col] = 1;
} else {
ptr_next[row][col] = 0;
}
}
}
}
// swap the pointers
bool (*tmp)[MAX_SIZE] = ptr;
ptr = ptr_next;
ptr_next = tmp;
}
Note that numAliveNeighbors
should probably take ptr
as an argument instead of implicitly via a global variable.