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

用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.

大意就是子程序的参数不允许是可变大小(或大小未知)的数组,而模块提供这种功能

但到底为什么不可以,以及当子程序的参数是可变大小的数组时程序发生了什么,实在搞不懂。

posted @ 2017-06-25 21:43  huangzc  阅读(3037)  评论(0编辑  收藏  举报