実行時まで形状を知らずに関数から配列を返す方法を考えています(想定形状配列を含む)。例を挙げて説明します。これは機能します
module foo
contains
function getArray(:)
real :: getArray(3)
integer :: i
do i=1,3
getArray(i) = 10.0*i
enddo
end function
end module
program xx
use foo
real :: array(3)
integer :: i
array = getArray()
print *, array
end program
自動配列を使用するため、これも機能します
module foo
contains
function getArray(length)
integer :: length
real :: getArray(length)
integer :: i
do i=1,length
getArray(i) = 10.0*i
enddo
end function
end module
program xx
use foo
real :: array(5)
integer :: i
array = getArray(5)
print *, array
end program
これはどうですか?それは有効なFortranですか?この場合、メモリリークがありますか
module foo
contains
function getArray()
real, allocatable :: getArray(:)
integer :: length
integer :: i
length = 5 ! coming, for example, from disk
allocate(getArray(length))
do i=1,length
getArray(i) = 10.0*i
enddo
! cannot call deallocate() or a crash occurs
end function
end module
use foo
real :: array(5,5) ! get max size from other means, so to have enough space
integer :: i
array = getArray()
! leaking memory here ? unexpected behavior ?
end program