问题
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