是否有必要在任何其他代码之前声明数组维度?例如,我编写了以下简化示例代码:
PROGRAM mytest
IMPLICIT NONE
INTEGER :: i, j, k, mysum
! Let array c be a k-by-k**2 array
! Determine k within the program by some means...for example,
mysum=0
DO i=1, 3
mysum=mysum+1
END DO
k=mysum
REAL, DIMENSION(k, k**2) :: c
WRITE(*,*) "k=", k
WRITE(*,*) "k**2=", k**2
WRITE(*,*)
DO i=1,size(c,1)
WRITE(*,"(100(3X,F3.1))") (c(i,j), j=1,size(c,2))
END DO
END PROGRAM mytest
我想说的是,我想创建一个c
的数组k
- 大小为k**2
,而k
是仅由代码中的其他计算确定; k
一开始就不为人所知。
但是,上面的代码在编译时给出了以下错误消息:
mytest.f90:13.31:
REAL, DIMENSION(k, k**2) :: c
1
Error: Unexpected data declaration statement at (1)
我的代码中的第13行是我最后声明c
的行:REAL, DIMENSION(k, k**2) :: c
。
另一方面,如果我改为声明k
并预先指定其尺寸,
PROGRAM mytest
IMPLICIT NONE
INTEGER :: i, j, k, mysum
REAL, DIMENSION(3,9) :: c
! Let array c be a k-by-k**2 array
! Determine k within the program by some means...for example,
mysum=0
DO i=1, 3
mysum=mysum+1
END DO
k=mysum
WRITE(*,*) "k=", k
WRITE(*,*) "k**2=", k**2
WRITE(*,*)
DO i=1,size(c,1)
WRITE(*,"(100(3X,F3.1))") (c(i,j), j=1,size(c,2))
END DO
END PROGRAM mytest
我得到了正确的输出:
k= 3
k**2= 9
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
但是,既然我事先并不知道k
,我在实际的代码中无法做到这一点。有没有办法在最初“声明”数组c
而不指定其尺寸,然后在知道k
的值后指定尺寸?
答案 0 :(得分:11)
您想使用可分配的数组:
PROGRAM mytest
IMPLICIT NONE
INTEGER :: i, j, k, mysum
REAL, DIMENSION(:,:), allocatable :: c !<- c is allocatable, rank 2
! Let array c be a k-by-k**2 array
! Determine k within the program by some means...for example,
mysum=0
DO i=1, 3
mysum=mysum+1
END DO
k=mysum
WRITE(*,*) "k=", k
WRITE(*,*) "k**2=", k**2
WRITE(*,*)
allocate(c(k,k**2)) ! <-- allocate array c with supplied shape
DO i=1,size(c,1)
WRITE(*,"(100(3X,F3.1))") (c(i,j), j=1,size(c,2))
END DO
deallocate(c) ! <-- deallocate when done
END PROGRAM mytest