动态数组等级 [英] Dynamic array rank
问题描述
我在模块中有一些动态的数组变量,后来在模块外部的两个子例程之一中分配了它们.但是,在一个子例程中,我希望数组为1D,在另一个子例程中,我希望数组为2D.
I have a few array variables in a module that are dynamic, and later allocated in one of two subroutines outside of the module. However, in one subroutine I want the array to be 1D, in the other subroutine I want it to be 2D.
原则上,我希望在模块中添加类似的内容,但是我不认为在声明区域中可以做到这一点?:
In principle I would want something like this in the module, but I don't believe this is possible in the declaration area?:
if (option1) then
real (kind=8), allocatable :: arr1(:)
else
real (kind=8), allocatable :: arr1(:,:)
endif
可分配的声明中是否存在使维动态化的方法?
Is there a way in the allocatable declarations to have the dimension be dynamic?
Edit1 :之所以这样做,是因为我正在向现有代码库添加新的子例程,但我想向后兼容. arr1仅由两个单独的子例程使用,主程序根本不使用它.这是一些更完整的代码,展示了这个想法:
The reason I'm doing this is I'm adding a new subroutine to an existing codebase, but I want to be backwards compatible. arr1 is only used by the two separate subroutines, the main program doesn't use it at all. Here is some more complete code showing the idea:
program myprog
use inputs
call read_inputs
if (option1) then
call do1
else
call do2
endif
contains
subroutine read_inputs
use inputs
use mymod
!!!read from file .logical. option1, integers N1, N2
!allocate arrays
if (option1) then
else
endif
end subroutine read_inputs
subroutine do1
use inputs
use mymod
allocate(arr1(N1))
!do stuff with arr1
end subroutine do1
subroutine do2
use inputs
use mymod
allocate(arr1(N1,N2))
!do stuff with arr1
end subroutine do2
end program
module inputs
logical :: option1
integer :: N1, N2
end module inputs
module mymod
use inputs
!!!!can I do something here to make the rank of arr1 dynamic? I don't think the following will work
if (option1)
real (kind=8), allocatable :: arr1(:)
else
real (kind=8), allocatable :: arr1(:,:)
endif
end module mymod
在mymod中,我可能只有两个单独的变量,即arr1和arr1_new.我只是希望避免这种情况.
I may just have two separate variable in mymod, arr1 and arr1_new. I was just hoping to avoid that.
推荐答案
我认为做这种事情的老套"方法是传递第一个元素,而不是传递整个数组和数组的大小:>
I think the 'olden' ways to do something like this is to pass the first element instead of the whole array and the size of the array separately:
program dyn_array
implicit none
integer :: a(2, 3)
integer :: i
call set1d(a(1,1), size(a))
do i = 1, 3
write(*, '(2I4)') a(:,i)
end do
contains
subroutine set1d(array, s)
implicit none
integer, intent(in) :: s
integer, intent(out) :: array(s)
integer :: i
do i = 1, s
array(i) = 3 * i
end do
end subroutine set1d
end program dyn_array
这篇关于动态数组等级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!