Fortran 中不同形状的可分配项的分配
Assignment of Allocatables of Different Shapes in Fortran
请看下面的代码:
program test
implicit none
integer, allocatable :: v1(:, :)
integer, allocatable :: v2(:, :)
allocate(v1(2, 4))
allocate(v2(2, 3))
v1(:, :) = reshape([11, 12, 13, 14, 15, 16, 17, 18], [2, 4])
v2(:, :) = reshape([21, 22, 23, 24, 25, 26], [2, 3])
print *, v1
print *, 'shape(v1): ', shape(v1)
print *
print *, v2
print *, 'shape(v2): ', shape(v2)
print *
v2 = v1
print *, v1
print *, 'shape(v1): ', shape(v1)
print *
print *, v2
print *, 'shape(v2): ', shape(v2)
print *
deallocate(v1)
deallocate(v2)
end program test
当我用 gfortran 编译它时,我得到以下输出:
11 12 13 14 15 16 17 18
shape(v1): 2 4
21 22 23 24 25 26
shape(v2): 2 3
11 12 13 14 15 16 17 18
shape(v1): 2 4
11 12 13 14 15 16 17 18
shape(v2): 2 4
当我用 ifort 编译它时,我得到以下输出:
11 12 13 14 15 16 17 18
shape(v1): 2 4
21 22 23 24 25 26
shape(v2): 2 3
11 12 13 14 15 16 17 18
shape(v1): 2 4
11 12 13 14 15 16
shape(v2): 2 3
哪个靠谱? ifort 或 gfortran 中有错误吗?
gfortran 版本 4.8.1
ifort 版本 14.0.0
默认情况下,ifort
版本 17 之前不使用 Fortran 2003 语义在赋值左侧重新分配可分配类型。 ifort 15 手册是这样说的(对于默认 norealloc-lhs
假设):
The compiler uses Standard Fortran rules when interpreting assignment statements. The left-hand side is assumed to be allocated with the correct shape to hold the right-hand side. If it is not, incorrect behavior will occur.
要允许分配的左侧重新分配到正确的形状,请使用选项 -assume realloc-lhs
进行编译。或者,您可以使用 -standard-semantics
进行编译,使所有假设默认符合 Fortran 2003 标准,并具有一些 Fortran 2008 功能。
请看下面的代码:
program test
implicit none
integer, allocatable :: v1(:, :)
integer, allocatable :: v2(:, :)
allocate(v1(2, 4))
allocate(v2(2, 3))
v1(:, :) = reshape([11, 12, 13, 14, 15, 16, 17, 18], [2, 4])
v2(:, :) = reshape([21, 22, 23, 24, 25, 26], [2, 3])
print *, v1
print *, 'shape(v1): ', shape(v1)
print *
print *, v2
print *, 'shape(v2): ', shape(v2)
print *
v2 = v1
print *, v1
print *, 'shape(v1): ', shape(v1)
print *
print *, v2
print *, 'shape(v2): ', shape(v2)
print *
deallocate(v1)
deallocate(v2)
end program test
当我用 gfortran 编译它时,我得到以下输出:
11 12 13 14 15 16 17 18
shape(v1): 2 4
21 22 23 24 25 26
shape(v2): 2 3
11 12 13 14 15 16 17 18
shape(v1): 2 4
11 12 13 14 15 16 17 18
shape(v2): 2 4
当我用 ifort 编译它时,我得到以下输出:
11 12 13 14 15 16 17 18
shape(v1): 2 4
21 22 23 24 25 26
shape(v2): 2 3
11 12 13 14 15 16 17 18
shape(v1): 2 4
11 12 13 14 15 16
shape(v2): 2 3
哪个靠谱? ifort 或 gfortran 中有错误吗?
gfortran 版本 4.8.1
ifort 版本 14.0.0
默认情况下,ifort
版本 17 之前不使用 Fortran 2003 语义在赋值左侧重新分配可分配类型。 ifort 15 手册是这样说的(对于默认 norealloc-lhs
假设):
The compiler uses Standard Fortran rules when interpreting assignment statements. The left-hand side is assumed to be allocated with the correct shape to hold the right-hand side. If it is not, incorrect behavior will occur.
要允许分配的左侧重新分配到正确的形状,请使用选项 -assume realloc-lhs
进行编译。或者,您可以使用 -standard-semantics
进行编译,使所有假设默认符合 Fortran 2003 标准,并具有一些 Fortran 2008 功能。