user1543042
user1543042

Reputation: 3442

Fortran pass an array to function

I am trying to pass an array of unknown length to a function. I would also prefer the indices of a is the same as b. Is this possible?

The program compiles but does run through the function.

Any help would be appreciated.

 function RealCumSum(i) result(j)
    real, dimension(1:), intent(in)  :: i ! input
    real, dimension(size(i)) :: j ! output
    integer :: m

    do m = 1,size(i)
        j(m) = sum(i(1:m))
    end do

 end function RealCumSum

 program xfunc
    implicit none
    real, dimension(2) :: a = (/ 3.2 , 2.5 /)
    real, dimension(2) :: b, RealCumSum

    b = RealCumSum(a)

    write(*,*) "cumulative sum of ",a," is ", b
 end program xfunc

Upvotes: 3

Views: 5945

Answers (1)

The assumed shape array arguments (dimension(:)) require an explicit interface. It is best done by placing the procedure in a module. The other options are to make the procedure internal (using contains) or to supply an interface block.

module m
 implicit none
contains
 function RealCumSum(i) result(j)
    real, dimension(1:), intent(in)  :: i ! input
    real, dimension(size(i)) :: j ! output
    integer :: m

    do m = 1,size(i)
        j(m) = sum(i(1:m))
    end do

 end function RealCumSum
end module

 program xfunc
    use m

    implicit none
    real, dimension(2) :: a = (/ 3.2 , 2.5 /)
    real, dimension(2) :: b, RealCumSum

    b = RealCumSum(a)

    write(*,*) "cumulative sum of ",a," is ", b
 end program xfunc

Upvotes: 4

Related Questions