Comparison of the strategy for comparing returned arrays

In Fortran, I can return arrays from a routine with three approaches. The first is through the intent(out) parameter. The second is through a function that has an array as result . The third should have a function that has a result pointer to an array that is allocated in the function.

What are the advantages and disadvantages of each approach?

+6
fortran fortran90
source share
2 answers

My practice is to use the return function when the function changes only one variable and does not make another exit. If several variables are changed or the procedure performs other actions, I would put the output variables in the argument list. This is a style choice. It is possible to create memory leaks with pointers, especially with pointers returned as arguments to a function, so I would avoid this option if there was no convincing reason in a particular case.

UPDATE: there is no problem with the argument of the intent array (out) ... no assumptions are needed about the size of the array, as shown in the following example:

 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 
+5
source share
  1. `intent (out)` can be a problem, since you need to make assumptions about the size of the transferred array.
  2. Returning an array is also a problem, since the receive code will have to make assumptions about the size of the returned array
  3. pointers to arrays have size problems plus the problem of making assumptions about whether the pointer is bound or not.
  4. An alternative is to create a module, and this module has a type that contains both a distributed array and an integer that details the size of the array:
 module mymodule type myvector double precision,allocatable::values(:) integer::length end type end module 

Then your function could be:

 function myvecreturner(someparam) use mymodule type(myvector)::myvecreturner integer::someparam allocate(myvecreturner%values(someparam)) myvecreturner%length = someparam end function 

And you can happily pass these types of myvector. Just remember to free arrays when you are done with them ...

0
source share

All Articles