CS120-03 Lab 13 Dynamic Conway Apr. 28, 2015

[Pages:3]CS120-03

Lab 13 ? Dynamic Conway

Apr. 28, 2015

Introduction: This lab will have you revisit the classic Conway's Game of Life. Previously, however, we would define the

dimensions of the world (the 2D array), but this time it will be done at run-time. As such, we have to dynamically allocate our arrays in our code.

Allocating a 2D array can be quite difficult, due to the series of steps that must be done. In this lab, we will be using a struct called Cell to represent each cell in the array (as opposed to using an int). What we must do, then, is create a 2D array of Cell pointers. Note, however, that dynamic 2D arrays are not truly a single block of memory with many rows and columns, but rather an array of pointers to other arrays that do not necessarily reside contiguouslyin memory.

In turn, we must perform two separate allocation steps. First, we need to allocate an array of p ointers to Cells based on the size of rows the user desires. This is done with the following command for this example:

Cell** grid = new Cell*[rows]; This statement will generate an array of Cell pointers, the size of which is determined by the rows variable. grid will now be an array of pointers to Cell structs, but, since they are not yet initialized to point to an instantiated object of type Cell, they are currently pointing at garbage. As such, we need to iterate through each Cell* in grid and point them to existing objects. That is done with the following loop:

for (int r = 0; r < rows; r++) Grid[r] = new Cell[cols];

Recall that the new keyword instantiates an object and returns a pointer to it. In this case, every time thro ugh the loop, we are creating a new array of Cell objects in memory and assigning the pointer to that array of objects that new creates to the current pointer in grid.

The following code implements this dynamic allocation technique to create a variably si zed game of Conway's. Notethe comments on which library to include and which sleep() function to use depending on where you are compiling. You should erase the code for the compiler you are not using.

Code:

#include #include #include #include // cols;

Cell** grid; // Notice the double pointer

grid = new Cell*[rows]; // ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download