2014-03-13 77 views
0

我有一個調用子函數的問題,該子函數返回大小未知的向量和數組。我不知道如何去掉我稱之爲函數的變量。該程序不會編譯,但隨着錯誤消息崩潰:Fortran:返回未知大小的向量和數組的調用子程序

Minnesegmentsfeil(核心轉儲)

這有點像在英語記憶段錯誤。

這是我的主要程序。

program transfer 
! use konstanter 
    implicit none 

! real :: f3eksitasjon 
! real :: amp, w, F3a, eta3a 

    real, allocatable, dimension(:) :: Aw, Vp, Vtot, Ym, Zm, Zt, Ds 
    real, allocatable, dimension(:,:) :: Spos 
    integer, allocatable, dimension(:) :: Ns, Dir 
    integer :: i, N 


    call geometry(N, Aw, Vp, Vtot, Ym, Zm, Zt, Ds, Ns, Spos, DIR) 

    print *, N, Aw(1), Vp(1), Vtot(1), Ym(1), Zm(1), Ds(1), Ns(1), Spos(1,1), Spos(1,2), Dir(1) 


end program transfer 

子程序幾何從文件讀取。向量的長度和數組的大小取決於它讀取的文件。

subroutine geometry(N, Aw, Vp, Vtot, Ym, Zm, Zt, Ds, Ns, Spos, DIR) 
    implicit none 

    integer, intent(out) :: N 
    real, dimension(:), allocatable, intent(out):: Aw, Vp, Vtot, Ym, Zm, Zt, Ds 
    real, dimension(:,:), allocatable, intent(out) :: Spos 
    integer, dimension(:),allocatable, intent(out) :: Ns, DIR 
    real, dimension(:), allocatable :: Bp, Hp, Lp, Vs 
    real, parameter :: pi = 4.0*atan(1.0) 
    integer :: i 


    open(unit = 11, file = "semisub.dat") 
    read(11,*) N 

    allocate(Aw(N)) 
    allocate(Vp(N)) 
    allocate(Vtot(N)) 
    allocate(Ym(N)) 
    allocate(Zm(N)) 
    allocate(Zt(N)) 
    allocate(Ds(N)) 
    allocate(Spos(N,4)) 
    allocate(Ns(N)) 
    allocate(DIR(N)) 
    allocate(Hp(N)) 


    do i = 1,N 
    read(11,*) Bp(i), Hp(i), Lp(i), Ym(i), Zm(i), DIR(i) 
    read(11,*) Ns(i), Ds(i) 

    If (Ns(i) > 8) STOP "Feil i semisub.dat. For mange sOyler" 

    read(11,*) Spos(i,1:Ns(i)) 


    end do 

    Zt(:) = Zm(:) + Hp(:)/2 
    Aw(:) = 2 * Ds(:) * Ns(:) 
    Vp(:) = 2 * Lp(:) * Bp(:) * Hp(:) 
    Vs(:) = 2 * Ns(:) * pi * (Ds/2)**2 * (-Zt(:)) 
    Vtot(:) = Vp(:) + Vs(:) 


end subroutine geometry 
+0

這是一個如何安排代碼的示例,以便主程序將「知道」如何調用子程序,如IanH所述:http://stackoverflow.com/questions/6511711/computing-the-cross -fortran-90 –

+0

在main程序中使用dimension(:)進行分配仍然是正確的,因爲主程序不知道子例程返回的維度? – SM411

+0

是的。如果在編譯時數組維數未知,則用'allocatable'屬性聲明。分配可以在子程序中完成,但主例程必須知道該維度是「可變的」。 –

回答

3

代碼如圖所示,缺少主程序範圍內子程序的顯式接口。該子例程需要顯式接口,因爲某些參數是可分配的。 (如果有明確的接口可用,則表示編譯器明確知道子例程接口的外觀 - 編譯器需要這些信息,因爲它通常需要做額外的工作來將可分配對象傳遞給可分配的僞參數)

將子程序放在模塊中,然後在主程序的規範部分中使用該模塊是給子程序一個明確界面的一種方法。另一種方法是使子程序成爲內部程序(將其放在主程序中的contains語句之後)。第三種方法是將子程序的接口塊放在主程序的規格部分。