Fortran:动态数组

声明:本博文翻译自:https://www.tutorialspoint.com/fortran/fortran_dynamic_arrays.htm

动态数组是一类其大小在编译时未知,但在执行时已知的数组。
动态数组使用可分配属性声明。
例如:
real, allocatable :: darray(:,:)
对其进行分配
allocate(darray(m,n))
对其进行释放
deallocate(darray)
这里再介绍一个函数allocated,用来检测数组是否被声明,返回一个逻辑值

测试代码如下:
Program dynamic_array 
  implicit none 

  !.. rank is 2, but size not known   
  real, dimension (:,:), allocatable :: darray    
  integer :: s1, s2     
  integer :: i, j     

  print*, "Enter the size of the array:"     
  read*, s1, s2      

  !.. allocate memory      
  allocate ( darray(s1,s2) )

  if (  allocated(darray) ) print*, "darray has been allocated!"

  do i = 1, s1           
    do j = 1, s2                
      darray(i,j) = i*j               
      write(*,'(a,g0,a,g0,a,3x,g0)') "darray(",i,",",j,") = ", darray(i,j)           
    end do      
  end do      

  deallocate (darray)  
end program dynamic_array
执行结果如下:
Enter the size of the array:
3 3
darray has been allocated!
darray(1,1) =    1.000000
darray(1,2) =    2.000000
darray(1,3) =    3.000000
darray(2,1) =    2.000000
darray(2,2) =    4.000000
darray(2,3) =    6.000000
darray(3,1) =    3.000000
darray(3,2) =    6.000000
darray(3,3) =    9.000000

这里顺便再介绍一个函数where的使用方法
where作用于数组或数组片段
Program whereStatement
  implicit none
  integer :: a(3,5), i , j

  do i = 1,3
    do j = 1, 5                
      a(i,j) = j-i          
    end do 
  end do

  Print *, 'The A array:'

  do i = lbound(a,1), ubound(a,1)
    write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
  end do

  where( a < 0 ) 
    a = 1 
  elsewhere
    a = 5
  end where

  Print *, 'The A array:'
  do i = lbound(a,1), ubound(a,1)
    write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
  end do   

End program whereStatement
运行结果如下:
The A array:
0           1           2           3           4
-1           0           1           2           3
-2          -1           0           1           2
The A array:
5           5           5           5           5
1           5           5           5           5
1           1           5           5           5

猜你喜欢

转载自blog.csdn.net/chd_lkl/article/details/82181386