How to pass allocatable arrays to subroutines in Fortran

前端 未结 3 1897
日久生厌
日久生厌 2020-11-27 06:38

The following code is returning a Segmentation Fault because the allocatable array I am trying to pass is not being properly recognized (size returns 1, when it should be 3)

3条回答
  •  余生分开走
    2020-11-27 07:24

    Please also note that your allocatable dummy argument array is declared with intent(in), which means its allocation status will be that of the associated actual argument (and it may not be changed during the procedure). The actual argument passed to your subroutine may be unallocated and therefore illegal to reference, even with an explicit interface. The compiler will not know this and the behaviour of inquiries like size is undefined in such cases.

    Hence, you first have to check the allocation status of array with allocated(array) before referencing its contents. I would further suggest to implement loops over the full array with lbound and ubound, since in general you can't be sure about array's bounds:

    subroutine subtest(array)
      double precision, allocatable, intent(in) :: array(:,:)
      integer                                   :: iii, jjj
    
      if(allocated(array)) then
        print*, size(array, 1), size(array, 2)
        do iii = lbound(array, 1), ubound(array, 1)
          do jjj = lbound(array, 2), ubound(array, 2)
            print*, array(iii,jjj)
          enddo
        enddo
      endif  
    end subroutine
    

提交回复
热议问题