Assignment of Allocatables of Different Shapes in Fortran [duplicate]

泄露秘密 提交于 2020-01-15 08:07:10

问题


Please look at the following code:

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

When I compile it with gfortran, I get the following output:

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

When I compile it with ifort, I get the following output:

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

which one is reliable? is there a bug in ifort or in gfortran?

gfortran version 4.8.1
ifort version 14.0.0


回答1:


By default, ifort before version 17 does not use Fortran 2003 semantics for reallocating an allocatable type on the left side of an assignment. The ifort 15 manual has this to say (for the default norealloc-lhs assumption):

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.

To allow the left side of the assignment to be reallocated to the proper shape, compile with the option -assume realloc-lhs. Alternatively you can compile with -standard-semantics to make all assumptions default to compliance with the Fortran 2003 standard, with some Fortran 2008 features.



来源:https://stackoverflow.com/questions/31006007/assignment-of-allocatables-of-different-shapes-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!