分配给未分配的变量
Assignment to unallocated variable
我的代码中有一行将一个数组分配给一个未分配的数组。我以为这是一个错误,但令我惊讶的是它工作得很好。
program test
implicit none
real, allocatable :: x(:,:)
real :: y(2,2)
y = 1.
x = y
print*, x
end program test
这在内存方面如何工作?这里的 =
运算符只是同时分配和赋值?为什么这是可能的,为什么编译器没有抱怨?我正在使用 gfortran 5.4.0.
这是正确的,根据第 7.2.1.3 节,WD 1539-1 的 "Interpretation of intrinsic assignments",第 3 段。
自 Fortran 2003 起,可分配数组将在 运行 时自动分配(或如果形状已更改则重新分配)。例如,参见 NAG 编译器的 Fortran 2003 特性 https://www.nag.com/nagware/np/r61_doc/nag_f2003.pdf or look for "realloc" in the documentation of gfortran https://gcc.gnu.org/onlinedocs/gfortran/Error-and-Warning-Options.html#Error-and-Warning-Options
我的代码中有一行将一个数组分配给一个未分配的数组。我以为这是一个错误,但令我惊讶的是它工作得很好。
program test
implicit none
real, allocatable :: x(:,:)
real :: y(2,2)
y = 1.
x = y
print*, x
end program test
这在内存方面如何工作?这里的 =
运算符只是同时分配和赋值?为什么这是可能的,为什么编译器没有抱怨?我正在使用 gfortran 5.4.0.
这是正确的,根据第 7.2.1.3 节,WD 1539-1 的 "Interpretation of intrinsic assignments",第 3 段。
自 Fortran 2003 起,可分配数组将在 运行 时自动分配(或如果形状已更改则重新分配)。例如,参见 NAG 编译器的 Fortran 2003 特性 https://www.nag.com/nagware/np/r61_doc/nag_f2003.pdf or look for "realloc" in the documentation of gfortran https://gcc.gnu.org/onlinedocs/gfortran/Error-and-Warning-Options.html#Error-and-Warning-Options