Bob the Robot
Bob the Robot

Reputation: 11

How to pass many temporary arrays to a subroutine in Fortran?

Suppose I'm writing a Fortran subroutine that performs one time step of a simulation, and so will be called repeatedly. To do its work, it requires many temporary arrays, which aren't meaningful or useful outside the subroutine. The user may wish to perform several simulations of different sizes during the program's execution, maybe concurrently, but the dimensions of the arrays will be the same for all the time steps of a particular simulation.

How should I handle these temporary arrays? Every way I can think of has some problem.

Is there a way to do this that avoids these problems? (Or is any of these problems less of a big deal than I think?)

Upvotes: 1

Views: 435

Answers (1)

Pierre de Buyl
Pierre de Buyl

Reputation: 7293

You can use the save attribute on the arrays.

subroutine step(x, t, do_allocattion)
    double precision, intent(in) :: x(:)
    double precision, intent(in) :: t
    logical, intent(in), optional :: do_allocation

    integer :: n
    double precision, allocatable, save :: work1(:), work2(:)
    n = size(x)

    if (present(do_allocation)) then
        if (do_allocation) then
            allocate(work1(n))
            allocate(work2(n))
        end if
    end if

    ! do work on x
end subroutine

EDIT: alternative solution, as I have mixed up with pointer arrays.

subroutine step(x, t)
    double precision, intent(in) :: x(:)
    double precision, intent(in) :: t

    integer :: n
    double precision, allocatable, save :: work1(:), work2(:)
    n = size(x)

    if (.not. allocated(work1)) then
        allocate(work1(n))
    end if
    if (.not. allocated(work2)) then
        allocate(work2(n))
    end if

    ! do work on x
end subroutine

EDITED: Caution: you cannot simply check for "allocatedness" as it will be undefined when the program is started and the subroutine executed for the first time. You can add another optional argument to deallocate. -> This is the case for pointer arrays.

Upvotes: 1

Related Questions