我想知道如何在运行时之前不知道形状的情况下从函数返回数组(包括假定的形状数组)。我会用例子来解释。这有效
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