Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to pass section of allocatable array as subroutine argument

Tags:

arrays

fortran

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?

like image 881
bob.sacamento Avatar asked Dec 08 '25 17:12

bob.sacamento


1 Answers

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.

like image 72
Vladimir F Героям слава Avatar answered Dec 10 '25 06:12

Vladimir F Героям слава



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!