尝试将可分配数组的一部分作为子例程参数传递
我想将可分配数组的一部分传递给子例程。源数组的维度由三个索引确定。该子例程需要一个具有两个索引的数组。假设我想对源数组的第五个索引进行操作。我做了类似的事情,但被最后一行抓住了:
module lots_of_stuff
...
contains
subroutine process_points(points)
integer, allocatable, intent(inout) :: points(:,:)
! do stuff
end subroutine
end module
program foo
use lots_of_stuff
integer, allocatable :: inpoints(:,:,:)
integer :: lim1, lim2, lim3
! figure out how big inpoints should be (i.e. set lim1, lim2, lim3) then ...
allocate(inpoints(lim1,lim2,lim3)
! populate inpoints then ...
call process_points(????)
假设我想处理入点第五部分中的元素。如果我尝试
call process_points(inpoints(:,:,5))
gnu fortran 告诉我
Error: Actual argument for ‘badpts’ must be ALLOCATABLE at (1)
如果我尝试
call process_points(inpoints(1,1,5))
gnu fortran 告诉我
Error: Rank mismatch in argument ‘badpts’ at (1) (rank-2 and scalar)
我想我可以将 inpoints(:,:,5)
复制到具有两个索引的数组并将其发送到 process_points
code>,但这看起来不优雅。有办法做我想做的事吗?
I want to pass a section of an allocatable array to a subroutine. The source array is dimensioned with three indices. The subroutine is expecting an array with two indices. Let's say I want to operate on the fifth index of the source array. I do something like this, but get caught on the last line:
module lots_of_stuff
...
contains
subroutine process_points(points)
integer, allocatable, intent(inout) :: points(:,:)
! do stuff
end subroutine
end module
program foo
use lots_of_stuff
integer, allocatable :: inpoints(:,:,:)
integer :: lim1, lim2, lim3
! figure out how big inpoints should be (i.e. set lim1, lim2, lim3) then ...
allocate(inpoints(lim1,lim2,lim3)
! populate inpoints then ...
call process_points(????)
Let's say I want to process the elements in the fifth section of inpoints. If I try
call process_points(inpoints(:,:,5))
gnu fortran tells me
Error: Actual argument for ‘badpts’ must be ALLOCATABLE at (1)
If I try
call process_points(inpoints(1,1,5))
gnu fortran tells me
Error: Rank mismatch in argument ‘badpts’ at (1) (rank-2 and scalar)
I guess I could copy inpoints(:,:,5)
to an array with two indices and send that to process_points
, but that seems inelegant. Is there a way to do what I am trying to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非您想释放或分配它,否则您不应该使
process_points(:)
中的虚拟参数可分配。或者,如果您想通过调用保留下限,但您的实际参数必须是可分配的。子数组永远不可分配,即使它是可分配数组的子数组。因此,决不能将子数组传递给需要可分配参数的子例程。
因此,我只需删除子例程中的
allocatable
属性即可。You should not make the dummy argument inside
process_points(:)
allocatable unless you want to deallocate it or allocate it. Or if you want to preserve the lower bound through the call, but then your actual argument must be allocatable.A subarray is never allocatable even if it is a subarray of an allocatable array. So you must never pass a subarray to a subroutine that requires an allocatable argument.
So I would just delete the
allocatable
attribute in the subroutine.