gpt4 book ai didi

arrays - 错误 : The part-name to the right of a part-ref with nonzero rank has the ALLOCATABLE attribute

转载 作者:行者123 更新时间:2023-12-01 09:56:04 31 4
gpt4 key购买 nike

我想使用子例程 sum_real 访问数组派生类型中数组的元素。即:对所有人的权重中的第一个条目求和。

type my_type
real, dimension(:), allocatable :: weight
real :: total_weight
end type my_type

type (my_type), dimension (:), allocatable :: people
type (my_type) :: answer

allocate (people (2))
allocate (people (1)%weight(2))
allocate (people (2)%weight(2))

people (1) % weight(1) = 1
people (2) % weight(1) = 1
people (1) % weight(2) = 3
people (2) % weight(2) = 3

call sum_real ( people (:) % weight(1), answer % total_weight )

我想要做的类似于 Array of derived type: select entry中找到的答案,除了我在数组派生类型而不是单个元素中分配了一个数组。

但是,我收到一个编译器错误:
error #7828: The part-name to the right of a part-ref with nonzero rank has the ALLOCATABLE attribute (6.1.2).   [WEIGHT]

最佳答案

如果您的组件是可分配的,则您尝试的操作是不可能的。引用( 6.1.2 )实际上是对官方标准文档的引用,禁止这样做。

原因很简单,可分配的组件(标量或数组)存储在与派生类型本身不同的内存部分。因此,如果你写

sum(people%total_weight)

或者
people%total_weight = 0

没问题, total_weight不可分配,它存储在派生类型中,编译器只是进入一个简单的循环并将一个又一个字段设置为零。可以知道每个 %totalweight的地址预先。

另一方面
sum(people%weight)

或者
people%weight = 0

每个 %weight存储在其他地方,您没有任何简单的公式来计算每个 %weight(i) 的位置.

如果可能,解决方案是固定数组的大小
real, dimension(2) :: weight

或使用 do 循环
s = 0
do i = 1, size(people)
S = S + sum(people(i)%weight)
end do

关于arrays - 错误 : The part-name to the right of a part-ref with nonzero rank has the ALLOCATABLE attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27183800/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com