簡體   English   中英

將2d數組作為1d參數fortran傳遞給子例程

[英]Pass 2d array to subroutine as 1d argument fortran

我想將2d數組傳遞給子例程,並將此數組視為1d參數。 我試圖通過這種方式傳遞它:subroutine(array(1,:))。 如果我明確定義數組,則此方法有效。 但是,如果數組是可分配的,則會出現以下錯誤:'array'的實際參數必須為ALLOCATABLE。如何進行這項工作?

這是一些簡短的示例代碼,上面給出了錯誤:

program array
implicit none
integer,dimension(:,:),allocatable::i

allocate(i(2,2))
i(1,1)=1

call array_method(i(1,:))

contains

subroutine array_method(i)
implicit none
integer,allocatable,dimension(:),intent(in)::i
write(*,*) i(1)
end subroutine array_method

end program array

如果我將代碼更改為顯式定義的數組,如下所示,則可以使用。 但是,我想使用可分配數組。

program array
implicit none
integer,dimension(2,2)::i

i(1,1)=1

call array_method(i(1,:))

contains

subroutine array_method(i)
implicit none
integer,dimension(2),intent(in)::i
write(*,*) i(1)
end subroutine array_method

end program array

如果我將子例程中的參數數組更改為可分配,並將傳遞的參數保留在主程序中作為顯式定義的數組(例如(2,2)),我仍然會遇到相同的錯誤。

在子例程array_method (第一個)中,將allocatable屬性賦予dummy參數。 這要求實際參數也具有該屬性。

但是,實際的參數是i(1,:) ,即使i本身也不能分配。

現在,根據在第一種情況下要執行的操作,啞元參數不需要具有allocatable屬性。 除非您想要更改分配狀態(不能給定intent(in) )或使用i的“實際”范圍,否則就可以不使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM