fortran子程序传入可变数组要在module里实现

坑死我了,我说怎么子程序传递不了可变数组

在写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
 
原文地址:https://www.cnblogs.com/ouyangping/p/7782677.html