Variable size arrays in Fortran without Allocate()
Is there a way to create variable size arrays in Fortran on the stack? Allocate() does not work for me, because it places the array on the heap. This may lead to problems with parallelization (see my other question: OpenMP开发者_开发知识库: poor performance of heap arrays (stack arrays work fine) ). Of course, some smart memory management would give a way around that problem, but memory management in Fortran sounds silly.
Essentially, I am looking for a Fortran equivalent of the following in C:
scanf("%d", N);
int myarray[N];
To re-iterate: I do NOT want
Integer, PARAMETER :: N=100
Integer, Dimension(N) :: myarray
because this determines the array size at compile time. Neither do I want
Integer, Dimension(:), Allocatable :: myarray
read(*,*) N
Allocate(myarray(1:N))
because it places the array on the heap.
Help very much appreciated. I was very happy with Allocatable arrays until my recent encounter with the problem in the question cited above. If there is a negative answer to this question, I would very much appreciate a link to the source.
Edit: see comments to M.S.B.'s answer. An elegant way of doing this only became possible in Fortran 2008, and it is done in a block
construct.
Fortran can automatically create arrays just with declarations on entry to subroutines, as long as the the dimensions are known at run time ... this doesn't require the dimensions to be declared parameter attribute, they can be arguments, e.g.,
subroutine MySub ( N )
integer, intent (in) :: N
real, dimension (N) :: array
is valid. So why not decide your size "N" in the main program, or some subroutine, then call another subroutine to continue. Likely with this approach the array will be on the stack. As @eriktous wrote, the Fortran language standard doesn't specify this behavior. Some compilers switch local arrays to the heap past a certain size. Some compilers provide options to control this behavior. Placing large arrays on the heap would probably be overridden with recursive or OpenMP.
You can also pass an allocatable array as an actual argument to a subroutine without the dummy argument of the subroutine being declared as allocatable. Which may not help with your concern because the original array will still likely be on the heap.
The Fortran standard has no concept of stack and heap, so this will be implementation (i.e. compiler) dependent. Looking at the docs for e.g. gfortran, it has an option
-frecursive Allow indirect recursion by forcing all local arrays to be allocated on the stack.
Other compilers may have similar options. Perhaps this does what you want.
精彩评论