What you try is not possible if your component is allocatable. The reference (6.1.2
) is actually a reference to the official standard documents, which prohibits this.
The reason is simple, the allocatable components (scalar or arrays) are stored in a different part of memory than the derived type itself. Therefore if you write
sum(people%total_weight)
or
people%total_weight = 0
it is no problem, total_weight
is not allocatable, it is stored within the derived type and the compiler just goes in a simple loop and sets one field after another to zero. You can know the address of each %totalweight
beforehand.
On the other hand
sum(people%weight)
or
people%weight = 0
each %weight
is stored elsewhere and you don't have any simple formula to compute where is each %weight(i)
.
The solution is either, to fix the size of the array, if possible
real, dimension(2) :: weight
or use a do loop
s = 0
do i = 1, size(people)
S = S + sum(people(i)%weight)
end do
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…