|
You frequently want to store more than one piece of information at each index in an array. For example, suppose you are storing information about mountains, where each mountain is assigned a number from 0 to some number numMountains, and you want to store two pieces of information for each mountain: the mountain's name and its elevation.
Start with a structure that describes a single mountain.
struct Mountain { const char* name; int elevation; };Now create an array of Mountain structures.
Mountain* mounts = new Mountain[maxNumMountains];(Notice that the physical size is maxNumMountains, as opposed to the logical size, numMountains, presumably defined later.) A convenient way to diagram array mounts to show a row for each array index and a column for each field of the structure.
How would you refer to the individual names and elevations in array mounts? Build up expressions step by step.
Variable mounts is an array of Mountain structures. So mounts[i] is a single Mountain, namely the one at index i.
Every structure of type Mountain has two fields called name and elevation. Since mounts[i] has type Mountain, you must be able to select a field of it. Write mounts[i].name and mounts[i].elevation.
Initially, all of the fields in array mounts are uninitialized. Let's initialize the name at index 0.
mounts[0].name = "Denali";Now, just for illustration, suppose you want to get the first letter of the name of mounts[0]. Field mounts[0].name has type const char*. It is an array of characters. Statement
char first = mounts[0].name[0];
sets first = 'D', the first character of mountain[0]'s name.
If you create an array of a structure type, then each thing in the array is automatically initialized using the parameterless constructor. For example,
Cell A[10];
creates an array of Cell values and initializes
each of them using the parameterless constructor.
Note. If there is at least one constructor for type S, but no parameterless constructor, then you are not allowed to create an array whose members have type S.
Note. An array of pointers is not automatically initialized. Declaration
Cell* P[maxNumCells];
creates an array of uninitialized pointer variables.
(The pointers are
dangling
until you store something into them.)
Refer to type Complex from a previous exercise. If you create an array of Complex values, how are the values in the array automatically initialized? Answer
If you create an array of Complex* values, how are they automatically initialized? Answer
|