Array Declaration and Indexing

Each language varies in the way that arrays are declared and indexed. Array indexing is a source-level consideration and involves no transformation of data. There are two differences in the way elements are indexed by each language:

The value of the lower array bound is different among Microsoft languages.

By default, FORTRAN indexes the first element of an array as 1. BASIC and
C index it as 0. Pascal lets you begin indexing at any integer value. Recent versions of BASIC and FORTRAN also give you the option of specifying lower bounds at any integer value.

Some languages vary subscripts in row-major order; others vary subscripts in column-major order.

This issue only affects arrays with more than one dimension. With row-major order (used by C and Pascal), the rightmost dimension changes first. With column-major order (used by FORTRAN, and BASIC by default), the leftmost dimension changes first. Thus, in C, the first four elements of an array declared as X[3][3] are

X[0][0] X[0][1] X[0][2] X[1][0]

In FORTRAN, the four elements are

X(1,1) X(2,1) X(3,1) X(1,2)

The preceding C and FORTRAN arrays illustrate the difference between row-major and column-major order as well as the difference in the assumed lower bound between C and FORTRAN. Table 11.6 shows equivalences for array declarations in each language. In this table, r is the number of elements of the row dimension (which changes most slowly), and c is the number of elements of the column dimension (which changes most quickly).

Table 11.6 Equivalent Array Declarations

Language Array Declaration Notes

BASIC DIM x(r–1, c–1) With default lower bounds of 0
C type x[r][c] struct { type x[r][c]; } x When passed by reference When passed by value
FORTRAN type x(c, r) With default lower bounds of 1
Pascal x : ARRAY [a..a+r–1, b..b+c–1] OF type,  

The order of indexing extends to any number of dimensions you declare. For example, the C declaration

int arr1[2][10][15][20];

is equivalent to the FORTRAN declaration

INTEGER*2 ARR1( 20, 15, 10, 2 )

The constants used in a C array declaration represent dimensions, not upper bounds as they do in other languages. Therefore, the last element in the C array declared as int arr[5][5] is arr[4][4], not arr[5][5].