Dynamic array in Fortran 77

2019-09-09 19:51发布

问题:

I have to write a subroutine in Fortran 77(i'm using Intel Fortran), which reads the measured values from a text file and stores them in a matrix.

Since the number of measured values is always variable, I must dynamically allocate the matrix.

I know that the dynamic allocation is only possible from Fortran 90, but at that time people had the same problems, so it is also possible. How would you proceed?

I do not want to reserve too much space for the matrix because the method is impractical for me.

回答1:

If you really are restricted to Fortran 77, you do not do dynamic allocation. Instead, declare an array that is larger than what you think you will likely need, without it being too large to prevent the program from running on your target system. Then store your values in that large array, separately keeping track of how many elements of the large array that you use. If your choice of array size was not large enough, let the user know and terminate the program.

People found the lack of dynamic allocation in Fortran 77 very restrictive, so they often resorted to using non-standard language extensions. If you decide to go down the path of language extensions, then these days the best extension to Fortran 77 to use in this situation is the allocatable array feature introduced with Fortran 90. I think it is fair to say that all actively maintained compilers that can handle Fortran 77 will also handle Fortran 90 allocatable arrays (and then some).



回答2:

As many people have pointed out, you don't have to stick to Fortran77, even if much of what is already written is Fortran77 compatible. Even the few features that have been deleted in Fortran 95 See Wikipedia for a list, your compiler will probably still work fine, as long as you don't switch from Fixed Form to Free Form in the same file.

Pre-F90, what people would probably do is to declare arrays that are (hoped to be) big enough for any use case, then only use the first elements of that array.

One thing that I am not certain about, but which might be useful, is the change of scope. Short example:

      subroutine main(n)
          implicit none
          integer n
          integer a(n)
          print*, "Please enter the ", n, " numbers"
          read*, a
          print*, "Sum is ", sum(a)
      end subroutine main

      program dynamic
          implicit none
          integer n
          print*, "Enter size of array:"
          read*, n
          call main(n)
      end program dynamic

I'm curious to know whether this would be Fortran77 compliant. I honestly don't know. @francescalus has convinced me that it isn't.