HP Fortran Programmer Guide (766160-001, March 2014)
Example 25 Example 8-5 pass_array.f90
PROGRAM main ! This program initializes a multi-dimensional array,
! displays its contents, then passes it to a C function,
! which displays its contents. The C function has the
! following declaration prototype:
!
! void get_array(int a[4][2]); !
! Note that the dimensions are declared in reverse order
! in C from the way they are declared in Fortran.
INTEGER, DIMENSION(2,4) :: my_array = &
RESHAPE(SOURCE = (/1,2,3,4,5,6,7,8/), SHAPE = (/2,4/)) PRINT *, 'Here is how Fortran stores the array:'
DO i = 1, 4
DO j = 1, 2
PRINT 10, j, i, my_array(j,i)
END DO
END DO
! There’s no need to use the %VAL or %REF built-in functions
! because both C and Fortran pass arrays by reference.
CALL get_array(my_array)
10 FORMAT(‘my_array(', I1, ',', I1, ') =', I2)
END PROGRAM main
Below is the source file for a HP Fortran program that calls a C function, passing a two-dimensional
array of integers.
The following is the source file for the C function.
Example 26 Example 8-6 get_array.c
#include <stdio.h>
/* get_array: displays the contents of the array argument*/
void get_array(int a[4][2])
{
int i, j;
printf("\nHere is the same array as accessed from C:\n\n");
for (i = 0; i < 4; i++)
for (j = 0; j < 2; j++)
printf(“a[%d][%d] = %d\n”, i, j, a[i][j]);
}
Here are the command lines to compile, link, and execute the program, followed by the output
from a sample run:
$ cc -Aa -c get_array.c
$ f90 pass_array.f90 get_array.o
$ a.out
Here is how Fortran stores the array:
my_array(1,1) = 1
my_array(2,1) = 2
my_array(1,2) = 3
my_array(2,2) = 4
my_array(1,3) = 5
my_array(2,3) = 6
my_array(1,4) = 7
my_array(2,4) = 8
Here is the same array as accessed from C:
a[0][0] = 1
a[0][1] = 2
a[1][0] = 3
a[1][1] = 4
a[2][0] = 5
a[2][1] = 6
a[3][0] = 7
a[3][1] = 8
Arrays 117