Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

memory - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...