将 2D 数组传递给需要 3D 数组的子程序

时间:2021-05-25 09:36:15

标签: arrays fortran

我需要使用一个需要 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

但是在第二个数组中复制整个数组只是为了适应等级,感觉既浪费又缓慢。有没有更好的方法来做到这一点?

1 个答案:

答案 0 :(得分:2)

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

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,*) 并且只使用传统的序列关联。

相关问题