Arrays in the Shell Game

The current implementation does seem somewhat awkward using the pointers and the pointer_to() function to access a selected shell.

If we think about it, the data associated with the insides or outsides of the shells are related - the 3 characters represent the status of the shells. It would be nice if we could have just one data structure to hold all of the information about the inside or outside of the shells.

C provides sucha data structure, called an array . An array is a compound data structure consisting of a collection of data cells, all of the same type, with a single name.

It is called a compound data structure because is contains more than one data item.

To use an array, as with any data structure, we need to know two things:

> How do we declare an array?
                        char contents[3];
As before, we give a type, a name, and in this case the size of the array. This declaration allocates 3 char cells (at adjacent locations in memory) and gives the entire structure the name contents.
> How do we access a cell in the array?
                        contents[0];
Each cell in the array has an index, an integer value that can be used to identify it. We use a subscripting expression consisting of an integer valued expression in square brackets together with the array name to identify a particular cell in the array. We can use these expressions to assign values to the cells:
                         contents[0] = 'P';

We can also use the expressions to retrieve a value from a cell:
     if( contents[guess] == 'P') ...

NOTE:

In C, when we declare an array of size n, the indexes of the cells are the integers 0 to n-1.

We can now rewrite the driver for the shell game using arrays to represent the shells in shell2.c and shuffle2.c.

Things to note about this code:

> The contents and backs data structures are arrays of characters.
> We no longer need the place variable, and the move and swap variables are now integers, to hold the index of the shells to swap and show the "hands".
> We no longer need the pointer_to() function; instead we access the shells directly using indexing expressions.
> We use the same swap_shells() function, passing it pointers to the two contents cells to be swapped.
> We must do an explicit check that the mark's guess is within the bounds of the array when checking if the guess is correct. C does not do "bounds checking" on array accesses.
> We use the same display() function, passing it the 3 characters from the appropriate array.

Why did we not pass the arrays to display()?

Because in shuffle2.c we also need to pass the constant characters for the headings.

Is there a way round this?


[up] to Overview.