将二维数组传递给期望三维数组的子例程



我需要使用一个期望3D数组作为输入的子例程,但我正在处理一个不需要第三维度的特殊情况。这个子程序被另一个处理这种特殊情况的子程序调用。

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 

我可能只需要创建一个可分配的3D数组,在其中存储2D数组中的值,比如这个

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

但是,在第二个数组中复制整个数组只是为了调整秩,这感觉很浪费,也很慢。有更好的方法吗?

其中一种方法是使用指针重新映射

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 

或者,您可以让foo接受显式大小的数组dimension(nx,ny)或假定大小的数组dimension(nx,*),并只使用传统的序列关联。

最新更新