In Fortran 90, do you need to declare array sizes in advance?

Do I need to declare array sizes before any other code? For example, I wrote the following simplified code example:

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 

What I'm trying to do is that I would like to create an array c , size k -by- k**2 in size, and k is determined only by other calculations inside the code; k unknown at the very beginning.

But the above code gives me the following error message at compile time:

 mytest.f90:13.31: REAL, DIMENSION(k, k**2) :: c 1 Error: Unexpected data declaration statement at (1) 

where line 13 in my code is the line where I finally declare c : REAL, DIMENSION(k, k**2) :: c .

On the other hand, if I instead declare k and indicate its dimensions at the top,

 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 

I get the correct output:

  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 

But, since I do not know k in advance, I cannot do just that in my actual code. Is there a way to β€œdeclare” an array c initially without specifying its size, and then specify the dimensions as soon as the value of k known?

+4
source share
1 answer

You want to use distributed arrays:

 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 
+10
source

All Articles