考虑以下子程序
subroutine myProc(m,n,flag,X)
Integer, intent(in) :: m,n
logical, intent(in) :: flag
real(8), intent(out), allocatable :: X(:,:)
if (flag) then
allocate(X(m,n))
! some more code here
else
allocate(X(m-1,n))
! some more code here
end if
end subroutine myProc
!!!!!!!!!!!!!!!!!!!
另外,如何在程序中调用此过程?假设我写
!... some code before
call myProc(5,6,.TRUE.,X)
我是否需要将 X 定义为 (4,6) 实数数组或将可分配数组传递给子例程?
在 Fortran 95 中是否可以做到所有这些?
最佳答案
在 Fortran 2003 及更高版本中将可分配的虚拟参数传递给子例程是非常好的。 IIRC TS(技术规范)首先允许 Fortran 95。今天所有的编译器都支持它。
当传递给可分配的虚拟参数时,不必分配实际参数。如果它恰好被分配,它实际上会被自动释放,因为虚拟是 intent(out)
和 allocatable, intent(out)
进入子例程时,参数会自动释放。
您的代码应该可以正常工作,但有一个重要方面,子例程必须具有显式接口(interface)。所以它必须放在一个模块中。或者它必须是内部的(在 contains
之后)或 interface
必须使用 block (丑陋)。
你可以像你展示的那样调用它
call myProc(5,6,.TRUE.,X)
和
X
不必分配。
关于arrays - 我可以在 Fortran 中使用可分配数组作为意图(输出)矩阵吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48472442/