24C. Arrays of Structures


Arrays of structures

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.


Compound selectors

How would you refer to the individual names and elevations in array mounts? Build up expressions step by step.

  1. Variable mounts is an array of Mountain structures. So mounts[i] is a single Mountain, namely the one at index i.

  2. 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.

  3. 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.