edgarmtze
edgarmtze

Reputation: 25048

Update two arrays in Fortran as in this C++ function

I have a C++ function which updates 2 arrays, with the arrays passed by reference:

double* CPPF(double array[],int size, double a1[], double a2[]){
    int m = size, n = size
    /* code that updates a1 and a2 arrays goes here */
    return 0;
}    

In my main function I have

var bigArray = new double[size*size];

for (int i = 0; i < dimension; i++){
   for (int j = 0; j <= i; j++)
       bigArray[i * size + j] = bigArray [j * size+ i] = Other[i,j];
}

double[] a1 = new double[size * size];
double[] a2 = new double[size];

double* RESULT = CPPF(bigArray, size, a1, a2);

// Use updated a1 and a2 

How would I define a Fortran function that updates these 2 arrays? I know that is possible because you do not pass arguments by values, only by reference.

I have so far tried something like:

REAL FUNCTION  FF(A, size, a1,a2)
   IMPLICIT  NONE
   INTEGER, INTENT(IN) :: size
   REAL :: A(:,:), a1(:),a2(:)
   !UPDATE a1 and a2 and finish   
END FUNCTION  FF

Upvotes: 1

Views: 374

Answers (2)

haraldkl
haraldkl

Reputation: 3819

Here is a translation including allocations:

module arrays_module
  implicit none
  ! Define a kind parameter for double precision real numbers.
  integer, parameter :: rk = selected_real_kind(16)

  subroutine CPPF(array, a1, a2)
    ! Use assumed shape arrays
    real(kind=rk) :: array(:)
    real(kind=rk) :: a1(:)
    real(kind=rk) :: a2(:)
    integer :: m, n

    ! Use the size of the arrays
    m = size(a2)
    n = size(a2)

    ! Do the setting of your arrays...
  end subroutine CPPF
end module arrays_module

program main
  use arrays_module
  implicit none

  integer :: dimension, n
  real(kind=rk) :: bigArray(:)
  real(kind=rk) :: a1(:), a2(:)
  real(kind=rk) :: Other(dimension, dimension)

  ! Allocating the arrays dynamically
  allocate(bigArray(n*n))
  allocate(a1(n*n))
  allocate(a2(n))

  do i=1,dimension
    do j=1,i
      bigArray((i-1)*n + j) = Other(i,j)
      bigArray((j-1)*n + i) = Other(i,j)
    end do
  end do

  call CPPF(array = bigArray, a1 = a1, a2 = a2)
  ! Use the updated arrays...
end program main

You could also have CPPF allocate the new arrays for you, if this is desirable.

Upvotes: 3

ev-br
ev-br

Reputation: 26040

What you're doing looks almost fine. Note only that Fortran's real is a single-precision float, an analog of C's float type.

I'm not sure what is the return value of your function. In Fortran you typically use subroutines if you don't return anything:

subroutine  FF(A, size1, a1,a2)
   IMPLICIT  NONE
   INTEGER, INTENT(IN) :: size1
   REAL*8, dimension(size1), intent(inout) :: A(size1,size1), a1(size1),a2(size1)

   A(1,1) = a1(1)*a2(1)

END subroutine FF


program blah
implicit none
 real*8 :: A(3,3), a1(3), a2(3)

 a1(1)=3.d0; a2(1)=2.d0;

 call ff(A,3,a1,a2)

 print*, A

end program blah

Upvotes: 2

Related Questions