在寫fortran程序的時候,要對矩陣實現特定的功能,如高斯法解線性方程組,很多時候子程序不知道矩陣的大小,如有限元程序中先要用程序得到總體剛度矩陣再把總剛傳入求解矩陣方程的子程序中。所以實現子程序參數是可變數組的功能要將子程序放在module中。具體如下:
主程序1(kk1.f90):
1 program main 2 implicit none 3 real,allocatable::a(:,:) 4 integer::np 5 allocate(a(2,3)) 6 a(1,:)=(/1.2,3.4,5.6/) 7 a(2,:)=(/1.2,3.4,5.6/) 8 call trya(a,np) 9 write(*,*)np 10 end program main
子程序1(try1.f90):
1 subroutine trya(a,np) 2 implicit none 3 real,intent(in),allocatable,dimension(:,:)::a 4 integer,intent(out)::np 5 np = size(a,2) 6 end subroutine trya
顯然該程序的目的是傳入一個事先不知道大小的矩陣到子程序中,子程序功能是求出返回矩陣的列數。
用gfortran編譯:gfortran try1.f90 kk1.f90 -o try 再運行try結果是 16368800 顯然出錯。
如果把子程序放在模塊中,如下:
主程序(kk.f90):
1 program main 2 use try 3 implicit none 4 real,allocatable::a(:,:) 5 integer::np 6 allocate(a(2,3)) 7 a(1,:)=(/1.2,3.4,5.6/) 8 a(2,:)=(/1.2,3.4,5.6/) 9 call trya(a,np) 10 write(*,*)np 11 end program main
子程序(try.f90):
1 module try 2 implicit none 3 contains 4 subroutine trya(a,np) 5 implicit none 6 real,intent(in),allocatable,dimension(:,:)::a 7 integer,intent(out)::np 8 np = size(a,2) 9 end subroutine trya 10 end module try
用gfortran編譯:gfortran try.f90 kk.f90 -o try 再運行try結果是 3 正確。
為什么會這樣,我也不是很清楚。
這篇學習資料中用句話:Unfortunately, allocatable arrays are not allowed to be passed as formal arguments to subprograms. The module construct provides a way for you to pass dynamically allocatable arrays to several program units.
大意就是子程序的參數不允許是可變大小(或大小未知)的數組,而模塊提供這種功能
但到底為什么不可以,以及當子程序的參數是可變大小的數組時程序發生了什么,實在搞不懂。