Fortran common variables, allocatable array

2020-02-15 02:08发布

问题:

is it possible to assign the size and values of a common array in a subroutine and then use it from other subroutines of the program?

The following program doesn't work, but I want to do something like this:

main.f

program main

integer n
integer, allocatable :: co(:)

common n, co

call assign

print *, co(1), co(2)

deallocate(co)
stop
end program main

assign.f

subroutine assign

integer n
integer, allocatable :: co(:)

common n, co

n = 2
allocate(co(n))

co(1) = 1
co(2) = 2

return
end subroutine assign

回答1:

No. You can put pointers into common, but not allocatables.

The reason is that a concept fundamental to common is storage association, where you can make a contiguous sequence of all the things that are in the common and those sequences are then shared amongst scopes. Allocatables can have their size vary dynamically in a scope, which would make the tracking in the sequence of things in the common block that came after the allocatable rather difficult.

(Typical implementation of allocatables means that the storage directly associated with the allocatable is just a descriptor - the actual data is kept elsewhere. This practically breaks the concept of a contiguous sequence of storage units, given that the allocation status (as recorded in the descriptor) and the data are both part of the value of the allocatable. The implementation for pointers is similar, but then conceptually the data that is elsewhere in memory is not part of the value of the pointer, so it should not be expected to appear in the contiguous sequence that the common describes - the pointer is in the sequence, but not what it points at.)

Allocatables require F90. That means that you can use module variables - which are a far better solution than the use of common for global data. If you must do this using common, then use a data pointer.