我有一個模塊中的幾個數組變量是動態的,稍後分配給模塊外的兩個子例程之一。但是,在一個子程序中,我希望數組是一維的,而在另一個子程序中,我希望它是二維的。動態數組排名
原則上我希望在模塊中這樣的事情,但我不相信這是可能的聲明區域?:
if (option1) then
real (kind=8), allocatable :: arr1(:)
else
real (kind=8), allocatable :: arr1(:,:)
endif
是否有可能分配申報辦法有維是動態的?
編輯1:我這樣做的原因是我添加一個新的子程序到現有的代碼庫,但我想向後兼容。 arr1僅由兩個獨立的子程序使用,主程序完全不使用它。下面是該理念的一些更完整的代碼:
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。我只是希望避免這種情況。
您可以使用執行該作業的子例程來重載'allocate'語句。 Fortran 90年齡將近26歲。你使用什麼編譯器?如果使用現代的Fortran(2003+)編譯器,我建議定義派生的數據類型,同時使用2維和3維可分配類型組件以及相應的類型綁定過程。 Fortran 90不允許這樣做,相反你必須使用容易發生內存泄漏的指針。 – jlokimlin
我不明白你的問題。數組在主程序或模塊中的外觀如何?那裏是1D還是2D?主程序或模塊是否關心子程序如何處理它(1D或2D)?也許你可以使用簡單的存儲關聯,但你應該顯示更多的代碼。 Ceterum censeo'kind = 8'很醜,臭和邪惡http://stackoverflow.com/a/856243/721644 –
@jlokimlin編譯器不是問題,但不幸的是,這是一個包含多個用戶的大型代碼庫,所以對於在可預見的將來,它將不得不成爲Fortran90。 – Michael