Home Segments Index Top Previous Next

457: Mainline

Maintaining parallel arrays, although simple, is awkward. It is safer and more elegant to package type information with the array elements. One way to do the packaging is to wrap a structure around both the trade-bearing union and a type-specifying integer:

struct tagged_trade { 
  int code; 
  union trade; 
} 

Then, you can define an array of tagged_trade objects:

struct tagged_trade *trade_pointers[100]; 

Given such an array, you determine type by extracting the value in the code structure variable, as in the following example, in which limit is an array index:

trade_pointers[limit] -> code 

Once you know what sort of object is stored in the union, you can go after the values stored. The following example, which assumes that the trade is a stock_trade object, illustrates:

                                 *-- Get stock_trade object  
                                 |   from trade object 
                                 v    
                              ------ 
trade_pointers[limit] -> trade.stock.pe_ratio 
                      --------      --------- 
                         ^              ^ 
                         |              *-- Get pe_ratio from 
                         |                  stock_trade object 
                         | 
                         *-- Get trade object from tagged_trade object