问题
I am using automatic allocation on assignment to calculate the difference of two arrays, with bounds starting at 0:
program main
implicit none
integer, allocatable :: a(:), b(:), c(:)
allocate(a(0:10))
allocate(b(0:10))
a = 1
b = 2
write (*,*) lbound(a)
write (*,*) lbound(b)
c = b - a
write (*,*) lbound(c)
end program main
Both, gfortran and ifort give the output:
0
0
1
Why doesn't c have the same bounds as a and b? Is there a short and concise (without an explicit allocate) way of making sure c has the same bounds?
回答1:
Why doesn't c have the same bounds as a und b?
Because it shall be allocated to the same shape as a
and b
and starting at 1. (Anyway b-a
is an expression and it starts at 1 as well, but it is not important. What if b
and a
start at different indexes?)
Is there a short and concise (without an explicit allocate) way of making sure c has the same bounds?
No. But you can at least explicitly allocate with mold=a
or source=a
.
回答2:
Consider an intrinsic assignment statement where the left-hand side is not allocated and is an array:
variable = expr
In such a case, the array variable
is allocated to the shape of the expression expr
, with lower bound equal to the value of LBOUND(expr)
(see Fortran 2018 10.2.1.3).
For the example of the question
c = b - a
the right-hand side is the expression b-a
. For this expression LBOUND(b-a)
is equal to 1: b-a
is not a whole array (F2018 16.9.109). The lower bound of c
on allocation is thus 1.
The only way the variable assigned to in intrinsic assignment with allocation to have lower bound not 1 is for the right-hand side to have lower bound not 1. In the assignment (c
not allocated)
c = b
then c
has lower bound that of b
.
You could avoid an explicit allocate statement with
c = b
c = c - a
but that is rather unclear and (to repeat a point in Vladimir F's answer) would you want the lower bound to be that of b
or a
if these differ.
For completeness:
allocate(c(7:17), source=b-a)
来源:https://stackoverflow.com/questions/56114861/preserve-bounds-in-allocation-in-intrinsic-assignment