HP Fortran Programmer's Guide (September 2007)
Calling C routines from HP Fortran
Arrays
Chapter 8186
Arrays
There are two differences between HP Fortran and C to consider when passing arrays from
Fortran to C:
• In HP Fortran, array subscripts start by default at 1, whereas in C they always start at 0
• In HP Fortran, multi-dimensional arrays are laid out differently in memory than they are
in C.
The difference in subscript-numbering does not result in any size discrepancies: an array of
10 elements in Fortran has 10 elements in C, too. But the subscripts in Fortran will be
numbered 1-10, whereas in C they will be numbered 0-9. This difference should not
require any change to the normal coding practice for C or for Fortran.
The difference in the way multi-dimensional arrays are laid out is well-known but more
significant: Fortran lays out multi-dimensional arrays in column-major order, so that the
leftmost dimension varies fastest; whereas C lays out multi-dimensional arrays in row-major
order, so that the rightmost dimension varies fastest.
Figure 8-1 shows the Fortran and C declarations for a two-dimensional array of integers, each
having the same number of rows and columns. The boxes under each array declaration
represents the memory locations where each element of the array is stored. As shown, each
language represents the six elements in a different order: the value stored at the first row and
second column is not the same for Fortran as for C.
Figure 8-1 Memory layout of a two-dimensional array in Fortran and C
To compensate for this difference, the dimensions of the array in either the C or Fortran code
should be declared in the reverse order of the other. For example, if the array is declared in
Fortran as follows:
int a[2][3];
INTEGER, DIMENSION(2,3) :: a
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]
a(1,1) a(2,1) a(1,2) a(2,2) a(1,3) a(2,3)