Arrays

Arrays are collections of like objects. The simplest case of an array is a vector. C++ provides a convenient syntax for declaration of fixed-size arrays:

Syntax

decl-specifiers dname [ constant-expressionopt ] ;

The number of elements in the array is given by the constant-expression. The first element in the array is the 0th element, and the last element is the (n-1th) element, where n is the size of the array. The constant-expression must be of an integral type and must be greater than 0.

Arrays are derived types and can therefore be constructed from the following:

Any user-defined or built-in type except void

Pointers to data or functions

Pointers to members

Enumerated types

Other arrays, except for arrays of references

Arrays constructed from other arrays are multidimensional arrays. These multidimensional arrays are specified by placing multiple [ constant-expression ] specifications in sequence. For example, consider this declaration:

int i2[5][7];

It specifies an array of type int, conceptually arranged in a two-dimensional matrix of five rows and seven columns, as shown in Figure 7.2.

In declarations of multidimensioned arrays that have an initializer-list (as described in “Initializers”), the constant-expression that specifies the bounds for the first dimension may be omitted. For example:

const int cMarkets = 4;

// Declare a float that represents the transporation costs.

double TransportCosts[][cMarkets] =

{ { 32.19, 47.29, 31.99, 19.11 },

{ 11.29, 22.49, 33.47, 17.29 },

{ 41.97, 22.09, 9.76, 22.55 } };

The above declaration defines an array that is three rows by four columns. The rows represent factories and the columns represent markets to which the factories ship. The values are the transportation costs from the factories to the markets. The first dimension of the array is left out, but the compiler fills it in by examining the initializer.

The technique of omitting the bounds specification for the first dimension of a multidimensioned array can also be used in function declarations as follows:

#include <float.h> // Includes DBL_MAX.

#include <iostream.h>

const int cMkts = 4;

// Declare a float that represents the transportation costs.

double TransportCosts[][cMkts] =

{ { 32.19, 47.29, 31.99, 19.11 },

{ 11.29, 22.49, 33.47, 17.29 },

{ 41.97, 22.09, 9.76, 22.55 } };

// Calculate size of unspecified dimension.

const int cFactories = sizeof TransportCosts /

sizeof( double[cMkts] );

double FindMinToMkt( int Mkt, double TransportCosts[][cMkts],

int cFacts );

main(int argc, char *argv[] )

{

double MinCost;

MinCost = FindMinToMkt( *argv[1] - '0', TransportCosts,

cFacts );

cout << "The minimum cost to Market " << argv[1] << " is: "

<< MinCost << "\n";

return 0;

}

double FindMinToMkt( int Mkt, double TransportCosts[][cMkts],

int cFacts )

{

double MinCost = DBL_MAX;

for( int i = 0; i < cFacts; ++i )

MinCost = (MinCost < TransportCosts[i][Mkt]) ?

MinCost : TransportCosts[i][Mkt];

return MinCost;

}

The function FindMinToMkt is written such that adding new factories does not require any code changes, just a recompilation.

Using Arrays

Individual elements of arrays are accessed using the array subscript operator ([ ]). If a singly dimensioned array is used in an expression with no subscript, the array name evaluates to a pointer to the first element in the array. For example:

char chArray[10];

...

char *pch = chArray; // Pointer to first element.

char ch = chArray[0]; // Value of first element.

ch = chArray[3]; // Value of fourth element.

When using multidimensioned arrays, various combinations are acceptable in expressions. The following example illustrates this:

double multi[4][4][3]; // Declare the array.

double (*p2multi)[3]; // Pointer to two-dimensional array.

double (*p1multi); // Pointer to four-dimensional array.

cout << multi[3][2][3] << "\n"; // Use three subscripts.

p2multi = multi[3]; // Make p2multi point to

// fourth "plane" of multi.

p1multi = multi[3][2]; // Make p1multi point to

// fourth plane, second row

// of multi.

In the preceding code, multi is a three-dimensional array of type double.The p2multi pointer points to an array of type double of size three, and p1multi is a pointer to an array of type double. The array is used with one, two, and three subscripts in this example. Although it is more common to specify all the subscripts, as in the cout statement, it is sometimes useful to select a specific subset of array elements as shown in the succeeding statements.

Arrays in Expressions

When an identifier of an array type appears in an expression other than sizeof, address-of (&), or initialization of a reference, it is converted to a pointer to the first array element. For example:

char szError1[] = "Error: Disk drive not ready.";

char *psz = szError1;

The pointer psz points to the first element of the array szError1. Note that arrays, unlike pointers, are not modifiable l-values. Therefore, the following assignment is illegal:

szError1 = psz;

Interpretation of Subscript Operator

Like other operators, the subscript operator ([ ]) can be redefined by the user. The default behavior of the subscript operator, if not overloaded, is to combine the array name and the subscript using the following method:

*((array-name) + (subscript))

As in all addition that involves pointer types, scaling is performed automatically to adjust for the size of the type. Therefore, the resultant value is not subscript bytes from the origin of array-name; rather, it is the subscriptth element of the array. (For more information about this conversion, see “Additive Operators” in Chapter 4, on topic .)

Similarly, for multidimensional arrays, the address is derived using the following method:

*((array-name) + (subscript1 * subscript2... * subscriptn))

Indirection on Array Types

Use of the indirection operator (*) on an n-dimensional array type yields an n–1 dimensional array. If n is 1, a scalar (or array element) is yielded.

Ordering of C++ Arrays

C++ arrays are stored in row-major order. Row-major order means the last subscript varies the fastest.