Fortran stores array elements in ascending storage units in column-major order. C stores array elements in row-major order. Fortran array indexes start at 1, while C array indexes start at 0.
The following example shows how a two-dimensional array that is declared by A(3,2) is stored in Fortran and C.
Fortran Element Name | C Element Name | |
---|---|---|
Lowest storage unit | A(1,1) | A[0][0] |
A(2,1) | A[0][1] | |
A(3,1) | A[1][0] | |
A(1,2) | A[1][1] | |
A(2,2) | A[2][0] | |
Highest storage unit | A(3,2) | A[2][1] |
REAL, DIMENSION(4,8) :: A, B(10)
! Pass an entire 4 x 8 array.
CALL CFUNC( A )
! Pass only the upper-left quadrant of the array.
CALL CFUNC( A(1:2,1:4) )
! Pass an array consisting of every third element of A.
CALL CFUNC( A(1:4:3,1:8) )
! Pass a 1-dimensional array consisting of elements 1, 2, and 4 of B.
CALL CFUNC( B( (/1,2,4/) ) )
Where necessary, the Fortran program
constructs a temporary array and copies all the elements into contiguous storage.
In all cases, the C routine needs to account for the column-major layout of
the array.! This explicit interface must be changed before the C function
! can be called.
INTERFACE
FUNCTION CFUNC (ARRAY, PTR1, PTR2)
INTEGER, DIMENSION (:) :: ARRAY ! Change this : to *.
INTEGER, POINTER, DIMENSION (:) :: PTR1 ! Change this : to *
! and remove the POINTER
! attribute.
REAL, POINTER :: PTR2 ! Remove this POINTER
! attribute or change to TARGET.
END FUNCTION
END INTERFACE