是否有必要分配可分配的数组?

1 fortran allocation

我有一个关于派生类型和分配数组的简单问题.假设我们已经定义了类型

type demo_type
        real(kind=8),allocatable :: a(:)
end type demo_type
Run Code Online (Sandbox Code Playgroud)

和功能

function demo_fill(n) result(b)
        integer, intent(in) :: n
        real(kind=8) :: b(n)
        b = 1.d0
end function demo_fill
Run Code Online (Sandbox Code Playgroud)

在主程序中写入是否正确

type(demo_type) :: DT
DT%a = demo_fill(3)
Run Code Online (Sandbox Code Playgroud)

或者是否有必要首先分配DT%a以防止意外覆盖内存中的其他变量?

type(demo_type) :: DT
allocate(DT%a(3))
DT%a = demo_fill(3)
Run Code Online (Sandbox Code Playgroud)

他们都编译,但我想知道哪种方法是正确的.谢谢!

Vla*_*r F 7

在Fortran 2003中,任何可分配的数组都可以在赋值时自动分配.

在你的情况下

DT%a = demo_fill(3)
Run Code Online (Sandbox Code Playgroud)

DT%a如果之前尚未分配给此形状,则会导致自动分配到右侧的形状,这是该功能的结果.

此行为是标准的,但某些编译器默认情况下不启用它,特别是Intel Fortran.您必须使用特殊的编译器标志来启用它(-standard-semantics,-assume realloc_lhs)

作为旁注,kind=8并不意味着所有编译器上的8字节实数,并且这种用法不受欢迎(请参阅/sf/answers/59937041/).