< previous page page_723 next page >

Page 723
Another Way of Defining Two-Dimensional Arrays
We hinted earlier that a two-dimensional array can be viewed as an array of arrays. This view is supported by C++ in the sense that the components of a one-dimensional array do not have to be atomic; they can also be structured. For example, in the Exam program in Chapter 12, we slipped in the declaration of a two-dimensional array. The student array was declared as:
const int MAX_LENGTH = 200;
typedef char String10[11];        // Room for 10 characters plus \0

String10 student[MAX_LENGTH];     // Array of student names
With this declaration, the components of the array student are one-dimensional arrays of type String10. In other words, student has two dimensions. We can access each row as an entity: student[57] accesses the name of student number 57. We can also access each individual component of student by specifying both indices: student[57][0] accesses the first letter in the name of student 57.
Now that you know how to declare a two-dimensional array, student can be redeclared as follows:
char student[MAX_LENGTH][11];
Does it matter which way we declare a two-dimensional array? Not to C++. The choice should be based on readability and understandability. Sometimes the features of the data are shown more clearly if both indices are specified in a single declaration. At other times, the code is clearer if one dimension is defined first as a one-dimensional array type.
Here is an example of when it is advantageous to define a two-dimensional array as an array of arrays. If the rows have been defined first as a one-dimensional array type, each can be passed to a function expecting as a parameter a one-dimensional array of the same type. The following function reads a student name into a variable of type String10, returning both the name and its length.
#include <string.h>    // For strlen()
  .
  .
  .

void GetAName( /* out */ String10 stuName,    // Input name
               /* out */ int&     length  )   // Length of name

// Reads a name from input until either \n or the maximum
// length is reached. Also returns the length of the name

 
< previous page page_723 next page >