How to declare a variable mid-routine in Fortran

后端 未结 4 1134
难免孤独
难免孤独 2020-12-07 03:56

I would like to create an array with a dimension based on the number of elements meeting a certain condition in another array. This would require that I initialize an array

4条回答
  •  旧时难觅i
    2020-12-07 04:19

    You need to use an allocatable array (see this article for more on it). This would change your routine to

    subroutine example(input_array,output_array)
    
      real,intent(in) :: input_array(50) ! passed array of known dimension
      real, intent(out), allocatable :: output_array(:)
      integer :: element_count, i
    
      element_count = 0
      do i=1,50
        if (some_array.gt.0) element_count = element_count+1
      enddo
    
      allocate(output_array(element_count))
    
    end subroutine
    

    Note that the intents may not be necessary, but are probably good practice. If you don't want to call a second array, it is possible to create a reallocate subroutine; though this would require the array to already be declared as allocatable.

提交回复
热议问题