Declaring and Indexing Arrays

Declaring and Indexing Arrays

Visual Studio 6.0

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

  • The value of the lower array bound is different.

    By default, Fortran indexes the first element of an array as 1. C and C++ index it as 0. Fortran subscripts should therefore be 1 higher. (Fortran also provides the option of specifying another integer lower bound.)

  • C varies subscripts in row-major order, Fortran in column-major order.

The differences in how subscripts are varied only affect arrays with more than one dimension. With row-major order (C and C++), the rightmost dimension changes fastest. With column-major order (Fortran), the leftmost dimension changes fastest. 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, and also the difference in the assumed lower bound between C and Fortran. The following table shows equivalencies for array declarations in each language. In this table, r is the number of elements of the row dimension (which changes the slowest), and c is the number of elements of the column dimension (which changes the fastest).

Equivalent Array Declarations

Language Array declaration Array reference
C/C++ type x[r][c], or struct { type x[r][c]; } x 1 x[r][c]
Fortran type x(c, r) x(c+1, r+1)

1. Use a structure to pass an array by value in C and C++.

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].

The following code provides a complete example, showing how arrays are passed as arguments to a routine.


      INTERFACE TO SUBROUTINE Pass_Arr [C,ALIAS:'_Pass_Arr'] ( Array )
      INTEGER*4 Array( 10, 10 )

      INTEGER*4 Arr( 10, 10 )
      CALL Pass_Arr( Arr )
      write (*,*) 'Array values: ', Arr(1, 10), Arr(2, 10)

/*     File CF.C  */

#include <stdio.h>

void Pass_Arr ( int arr[10][10] )
    arr[9][0] = 10;
    arr[9][1] = 20;
© 2015 Microsoft