Fortran中可分配数组能否用作intent(out)矩阵及调用方法咨询
Fortran可分配数组作为
intent(out)哑元的问题解答 没问题,我来一步步解答你的三个问题:
1. 能否将可分配数组用作intent(out)类型的矩阵?
完全可以!这是Fortran里非常实用的用法。当哑元被声明为intent(out), allocatable时,有个关键行为:进入子程序时,如果这个哑元之前已经分配过内存,会自动被释放。这就给了你在子程序内部根据逻辑重新分配数组大小的自由,正好匹配你给出的myProc子程序里根据flag选择不同维度的需求。
2. 如何调用该子程序?
你必须传递一个可分配数组作为实参,绝对不能预先定义成固定大小的数组(比如real(8) X(4,6)这种)。因为哑元是allocatable类型,实参必须和哑元类型匹配——也就是同样是可分配的,而且不需要预先分配内存,子程序内部会负责完成分配。
给你一个完整的调用示例:
program test_myProc implicit none real(8), allocatable :: X(:,:) ! 声明为可分配数组,不预先分配 ! 调用flag为.TRUE.的情况,X会被分配成(5,6) call myProc(5,6,.TRUE.,X) print *, "X的形状(flag=.TRUE.):", shape(X) deallocate(X) ! 用完手动释放,是个好习惯 ! 调用flag为.FALSE.的情况,X会被分配成(4,6) call myProc(5,6,.FALSE.,X) print *, "X的形状(flag=.FALSE.):", shape(X) deallocate(X) contains ! 把你的子程序放在程序的contains块里,或者单独放在模块中 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)) ! 这里可以添加你的业务代码,比如初始化X else allocate(X(m-1,n)) ! 其他业务代码 end if end subroutine myProc end program test_myProc
3. 这些操作在Fortran 95中是否可行?
完全可行!Fortran 95已经正式支持可分配数组作为哑元,包括intent(out)的场景。不过有个小建议:最好把子程序放在模块里(或者显式声明接口块),这样编译器能正确检查实参和哑元的兼容性,避免因为隐式接口导致的潜在问题。比如用模块的写法:
module my_subroutines implicit none contains 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)) else allocate(X(m-1,n)) end if end subroutine myProc end module my_subroutines program test_myProc use my_subroutines implicit none real(8), allocatable :: X(:,:) call myProc(5,6,.TRUE.,X) print *, shape(X) deallocate(X) call myProc(5,6,.FALSE.,X) print *, shape(X) deallocate(X) end program test_myProc
内容的提问来源于stack exchange,提问作者Pitt Prog
相关产品推荐
相关产品推荐

