< previous page page_727 next page >

Page 727
number of sales in store 1, during June, for item number 4, in department C, we simply access the array element
sales[1][5][4][C]
When a multidimensional array is declared as a formal parameter in a function, C++ requires you to state the sizes of all dimensions except the first. For our four-dimensional version of SalesType, a function heading would look either like
void DoSomething( /* inout */ int arr[][12][NUM_ITEMS][NUM_DEPTS] )
or, better yet, like
void DoSomething( /* inout */ SalesType arr )
The second version is the safest (and the most uncluttered to look at). It ensures that the sizes of all dimensions of the formal parameter match those of the actual parameter exactly. With the first version, the reason why you must declare the sizes of all but the first dimension is the same as we discussed earlier for two-dimensional arrays. Because arrays are stored linearly in memory (one array element after another), the compiler must use this size information to locate correctly an element that lies in the middle of the array.
SOFTWARE ENGINEERING TIP
Choosing a Data Structure
We have now seen two different data structures that can be used to represent data arranged as a table: parallel arrays and two-dimensional arrays. We can always use parallel arrays instead of a two-dimensional array. How do we decide which is most appropriate?
Recall that, in an array, all the components are of the same type; they represent the same thing. But what if we want to process information on the number of items sold, the cost of each item, and the percent tax to be charged for each item? We can define a table with the following headings to hold this information:
Item Number Number Sold Cost per Item Tax Rate
If we keep the item number and number sold as floating point numbers, we can define a two-dimensional array of type float with four columns, each corresponding to one of the headings; however, in this case, four parallel arrays are more appropriate.

(text box continues on next page)

 
< previous page page_727 next page >