【问题标题】:intent(out) and allocatable Fortran arrays: what is really done?intent(out) 和可分配的 Fortran 数组:真正做了什么?
【发布时间】:2023-02-08 17:22:52
【问题描述】:

我在 Stack Overflow 上的许多帖子中读到,当一个可分配数组被传递到一个子例程中时,它被释放,其中虚拟参数是 intent(out)。

如果我考虑以下代码:

program main

 real, dimension(:), allocatable :: myArray
 integer :: L=8

 allocate(myArray(1:L))
 call initArray(myArray)
 print *, myArray
 
contains

 subroutine initArray(myArray)
 real, dimension(:), intent(out) :: myArray

 myArray(:) = 10.0
 
 end subroutine initArray
 
end program main

输出是正确的。因此,当发生释放时,内存被释放但数组形状保持不变。准确吗?任何详细的解释将不胜感激。

我阅读了关于该主题的不同帖子(Can I use allocatable array as an intent(out) matrix in Fortran?What is the effect of passing an allocatable variable into a subroutine with non-allocatable argument?、...)。所以我知道数组已被释放,但我想了解它是什么意思,因为在我的代码中,大小保持不变,我也很惊讶这段代码有效。

【问题讨论】:

    标签: fortran allocatable-array


    【解决方案1】:

    你有点误解这里发生的事情。

    在使用 intent(out) 进入过程时释放的数组是那些对应于可分配虚拟对象的可分配数组。

    intent(out) 对一个论点的意义完全取决于论点的特征假的不是实际的争论。

    对应于普通伪参数的可分配实际参数是不是释放。 (如果是,则必须不分配不可分配的虚拟参数!)

    相反,实际参数的分配状态保持不变,假定(非延迟)形状虚拟参数的形状保持不变。

    伪参数变为未定义,作为 intent(out)。对于此处的普通伪参数,它仅指其值(在该赋值语句中立即定义)。

    【讨论】:

      【解决方案2】:

      释放发生在伪论证是可分配的并且intent(out)。尝试

      real, dimension(:), intent(out), allocatable :: myArray
      

      实现这一目标。

      事实上实参在主程序中是可分配的对于没有可分配的虚拟参数(比如你的)的子程序来说是无关紧要的。

      我强烈建议对主程序中的数组和子例程中的参数进行不同的命名,以便更好地看出差异。

      program main
      
       real, dimension(:), allocatable :: mainArray
       integer :: L=8
      
       allocate(mainArray(1:L))
       call initArray(mainArray)
       print *, mainArray
       
      contains
      
       subroutine initArray(argArray)
       real, dimension(:), intent(out) :: argArray
      
       argArray(:) = 10.0
       
       end subroutine initArray
       
      end program main
      

      现在,mainArray实参, argArray伪论证.虚拟参数必须是可分配的才能发生释放。

      【讨论】:

      • 主程序中的实际参数是可分配的这一事实很重要。虚拟可分配数组的实际参数必须是可分配的,否则会出现编译错误。
      • 当然可以,但这是一个不同的约束。
      猜你喜欢
      • 1970-01-01
      • 2015-12-18
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多