Chris Pollett>Old Classes>PIC 10a, Spring
2000>Hw6>Hw6 FAQ
Spring 2000 PIC 10a HW6 FAQ Page
General questions and answers for this homework will be placed here
as they arise.
-
In the constructor it would be useful to be able to convert an
integer
to a SquareValues, how do I do this? This problem comes up when
you try to calculate the number of bombs in adjacent squares for a board
piece. If you add one to something of type SquareValues, C++ coerces the
result to something of type int. To make it a SquareValues again you
do: (SquareValues)(...your expression).
For example,
SquareValues a = (SquareValues)(ONE_UNSEEN +1); would set
a to be TWO_UNSEEN.
- How do I dynamically allocate a 2-dimensional array?
You need to do this for the board in the minesweeper game.
Here is an example for dynamically allocating an 2D-array of integers
of size rowsXcolumns. First, such a 2D-array is referenced by a pointer
to a pointer. We can declare this as
int **arr, rows, columns;
cin >> rows; //get values for the size of the array from user
cin >> columns;
We then allocate the rows...
arr = new int* [rows];
So arr is used to store the address of the location of where the first row
will be store. *arr (also written arr[0]) will be the location of the
0th row. arr[1] will be the address of the first row, etc. We now
have to allocate memory for these rows...
for(int i=0; i < rows; i++)
{
arr[i] = new int[columns];
}
At this point our 2D-array is created and we can use it as regular 2D-array.
- How do I deallocate a dynamically allocated 2D-array?
The idea is just the reverse process of the allocation above.
for(int i=0; i < rows; i++)
{
delete [] arr[i]; //delete's memory for row i
}
delete [] arr; //deletes the pointers to the rows.
-
What is the member function ~MineSweeper()? This is the destructor
for the class MineSweeper. When a object of a class is deleted
this destructor method is automatically called. The point of a destructor
is to free up any dynamically allocated memory that the object might have used.