Ich frage mich, wie man ein Array von einer Funktion ohne Kenntnis der Form bis zur Laufzeit (einschließlich der angenommenen Form Arrays) zurückgibt. Ich werde es mit Beispielen erklären. Dies funktioniertFunktion Array zurückgeben ohne definierte explizite Form
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
Dies funktioniert auch, weil es den Einsatz von automatischen Arrays
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
Was ist mit diesem macht man? ist es Fortran gültig? habe ich ein Speicherleck in diesem Fall
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
In Ihrem letzten Beispiel hat getArray zwei Dimensionen, aber Sie behandeln es als 1D-Array. Warum das? – canavanin
@canavanin: Tippfehler –