返回数组策略比较

Ste*_*ini 7 fortran fortran90

在Fortran中,我可以使用三种方法从子例程返回数组.第一个是通过intent(out)参数.第二个是通过具有阵列的函数result.第三个是具有作为result指向数组的指针的函数,该函数在函数中分配.

每种方法的优点和缺点是什么?

M. *_* B. 5

我的做法是在函数只改变一个变量而不进行其他输出时使用函数返回.如果更改了多个变量或者过程执行了其他操作,我会将输出变量放在参数列表中.这是一种风格选择.使用指针创建内存泄漏是可能的,特别是将指针作为函数参数返回,所以除非在特定情况下有令人信服的理由,否则我会避免使用此选项.

更新:intent(out)数组参数没有问题......不需要对数组的大小做任何假设,如下例所示:

module example_one

implicit none

contains

subroutine two_arrays ( in_arr, out_arr )

   integer, dimension (:), intent (in) :: in_arr
   integer, dimension (:), allocatable, intent (out) :: out_arr

   integer :: i, len

   len = size (in_arr)

   allocate ( out_arr (1:len) )

   do i=1, len
      out_arr (i) = 3 * in_arr (i)
   end do

return

end subroutine two_arrays

end module example_one


program test

use example_one

implicit none

integer, dimension (1:5)  :: in_arr = [ 1, 2, 4, 5, 10 ]
integer, dimension (:), allocatable :: out_arr

write (*, *) allocated ( out_arr)
call two_arrays ( in_arr, out_arr )

write (*, *) size (out_arr)
write (*, *) out_arr

write (*, *) allocated ( out_arr)
deallocate ( out_arr )
write (*, *) allocated ( out_arr)

stop

end program test
Run Code Online (Sandbox Code Playgroud)