Fortran 动态数组
动态数组是一个数组,其大小在编译时未知,但在执行时已知。
动态数组使用属性 allocatable 声明。
例如:
real, dimension (:,:), allocatable :: darray
数组的维度,必须提及,但是,要为这样的数组分配内存,您可以使用 allocate 函数。
allocate ( darray(s1,s2) )
使用数组后,在程序中,应使用解除分配函数释放创建的内存。
deallocate (darray)
实例
program dynamic_arrayimplicit none!rank is 2, but size not knownreal, dimension (:,:), allocatable :: darrayinteger :: s1, s2integer :: i, jprint*, "Enter the size of the array:"read*, s1, s2! allocate memoryallocate ( darray(s1,s2) )do i = 1, s1do j = 1, s2darray(i,j) = i*jprint*, "darray(",i,",",j,") = ", darray(i,j)end doend dodeallocate (darray)end program dynamic_array
结果如下:
Enter the size of the array: 3,4darray( 1 , 1 ) = 1.00000000darray( 1 , 2 ) = 2.00000000darray( 1 , 3 ) = 3.00000000darray( 1 , 4 ) = 4.00000000darray( 2 , 1 ) = 2.00000000darray( 2 , 2 ) = 4.00000000darray( 2 , 3 ) = 6.00000000darray( 2 , 4 ) = 8.00000000darray( 3 , 1 ) = 3.00000000darray( 3 , 2 ) = 6.00000000darray( 3 , 3 ) = 9.00000000darray( 3 , 4 ) = 12.0000000
数据声明的使用
数据语句可用于初始化多个数组,或用于数组段初始化。
数据语句的语法为:
data variable / list / ...
实例
program dataStatementimplicit noneinteger :: a(5), b(3,3), c(10),i, jdata a /7,8,9,10,11/data b(1,:) /1,1,1/data b(2,:)/2,2,2/data b(3,:)/3,3,3/data (c(i),i = 1,10,2) /4,5,6,7,8/data (c(i),i = 2,10,2)/5*2/Print *, 'The A array:'do j = 1, 5print*, a(j)end doPrint *, 'The B array:'do i = lbound(b,1), ubound(b,1)write(*,*) (b(i,j), j = lbound(b,2), ubound(b,2))end doPrint *, 'The C array:'do j = 1, 10print*, c(j)end doend program dataStatement
结果如下:
The A array:7891011The B array:1 1 12 2 23 3 3The C array:4252627282
Where 语句的使用
where 语句可以让您在表达式中使用数组的某些元素,具体取决于某些逻辑条件的结果。如果给定的条件为 true,它允许在元素上执行表达式。
实例
program whereStatementimplicit noneinteger :: a(3,5), i , jdo i = 1,3do j = 1, 5a(i,j) = j-iend doend doPrint *, 'The A array:'do i = lbound(a,1), ubound(a,1)write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))end dowhere( a<0 )a = 1elsewherea = 5end wherePrint *, 'The A array:'do i = lbound(a,1), ubound(a,1)write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))end doend program whereStatement
结果如下:
The A array:0 1 2 3 4-1 0 1 2 3-2 -1 0 1 2The A array:5 5 5 5 51 5 5 5 51 1 5 5 5