How to declare a variable mid-routine in Fortran

后端 未结 4 1128
难免孤独
难免孤独 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条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 04:03

    You can use allocatable arrays for this task:

    subroutine example(some_array)
    
    real             :: some_array(50)
    real,allocatable :: new_array(:)
    integer          :: i, element_count, status
    
    element_count = 0
    do i=lbound(some_array,1),ubound(some_array,1)
      if ( some_array(i) > 0 ) then
        element_count = element_count + 1
      endif
    enddo
    
    allocate( new_array(element_count), stat=status )
    if ( status /= 0 ) stop 'cannot allocate memory'
    
    ! set values of new_array
    
    end subroutine
    

提交回复
热议问题