Share allocatable Arrays

后端 未结 3 875
离开以前
离开以前 2021-01-23 01:06

I have some allocatable arrays which I need to share between some subroutines. I usually would just pass them as arguments or maybe write everything in a Module, but I\'m afraid

3条回答
  •  遇见更好的自我
    2021-01-23 01:44

    You can pass an allocatable array to procedure that isn't declared to use allocatable arrays, as long as the array is allocated before the call. (Of course, you can't use the array as an allocatable array in the procedure in which it is declared without that property.) Perhaps that will solve your problem. Allocate the array in the code that you write, than pass it as an argument to the FEM solver.

    Example code: (I'd normally put the function into a module but you say that you can't do that, so I write an example showing the case of not using a module.)

    function MySum ( RegArray )
    
    real :: MySum
    real, dimension (:), intent (in) :: RegArray
    
    MySum = sum (RegArray)
    
    end function MySum
    
    
    program TestArray
    
       implicit none
    
       interface AFunc
    
          function MySum ( SomeArray )
    
             real :: MySum
             real, dimension (:), intent (in) :: SomeArray
    
          end function MySum
    
       end interface AFunc
    
       real, dimension (:), allocatable :: AllocArray
       integer :: N
       real :: answer
    
       write (*, '("Input array size: ")', advance="no")
       read (*, *) N
    
       allocate ( AllocArray (1:N) )
       AllocArray = 1.0
    
       answer = MySum ( AllocArray )
       write (*, *) answer
    
    end program TestArray
    

    ---------- EDIT: Second Concept ---------

    Sharing an allocatable array between two subroutines, without the calling routine being "aware" of the array.

    module MySubs
    
       real, allocatable, dimension (:,:) :: array
    
    contains
    
    
    subroutine One ( x, y, ... N, M )
    
       integer, intent (in) :: N, M
    
       if ( .NOT. allocated (array) ) allocate ( array (N, M) )
    
    
    end subroutine One
    
    
    subroutine Two ( .... )
    
    
    end subroutine Two
    
    
    end module MySubs
    

    UPDATE: note: This approach can be used to pass information between the two routines without the main program having access the module ... for the question, without modifying the original main prpgram. Part of the example is how to allocate the arrays: the example does that by having the subroutine that would first use the array test whether the array is allocated -- if not, it allocates the array.

提交回复
热议问题