Reputation: 45
I need to use a subroutine that expects 3D array as input, but I am dealing with a special case where the third dimension is not required. This subroutine gets called by another one that deals with this special case.
subroutine my_special_case (array)
real, dimension(:,:) :: array
! some code
call foo (array)
end subroutine
subroutine foo (array)
real, dimension(:,:,:) :: array
! some code
end subroutine
I could probably just create an allocatable 3D array where to store the values in the 2D one like this
subroutine my_special_case (array)
real, dimension(:,:) :: array
real, allocatable, dimension(:,:,:) :: pass
! some code
allocate( pass( size(array,1), size(array,2), 1) )
pass(:,:,1) = array(:,:)
call foo (pass)
end subroutine
but it just feels wasteful and slow to copy the whole array in the second one just to adapt the rank. Is there a better way to do this?
Upvotes: 1
Views: 240
Reputation: 59998
One of the ways is to use pointer remapping
subroutine my_special_case (array)
real, dimension(:,:), target :: array
real, dimension(:,:,:), pointer :: ptr
ptr(1:size(array,1), 1:size(array,2), 1:1) => array
! some code
call foo (ptr)
end subroutine
subroutine foo (array)
real, dimension(:,:,:) :: array
! some code
end subroutine
Or you could make foo to accept an explicit size array dimension(nx,ny)
or an assumed-size array dimension(nx,*)
and just use traditional sequence association.
Upvotes: 2