Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Allocatable array as argument in F90 1

Status
Not open for further replies.

fanta2

Technical User
Apr 10, 2005
78
CA
This is an extension of my previous post - passing allocatable array between subroutines...thanks xwb for that! I have an allocatable array (assumed shape array) in a subroutine - where it's size determined in the subroutine and I want to use this array in the main program. How can it be done?

Code:
Program calc2
real, allocatable:: y(:)

how it can be allocated and get the values of y from subroutine x

End program calc2
!----------------------------------------
Subroutine x(y??)

real, allocatable :: y(:)
integer:: n

call --
call --

process size of y

allocate (y(n))

call --- get values of y

processs---

End subroutine x
 
The only way I know of doing this in F90 is to pass the size of the array back to the owner of the allocatable array so that the owner can allocate the space.

The owner doesn't have to be a routine. It can be a module so the module can do the allocation and with the use clause, you can use the array anywhere.
 
Thanks xwb! Can you give me an example of what you have stated, please?
 
Something like this - it works like a global
Code:
module Dyn
   ! This is owned by the module
   integer, allocatable:: dyna(:)
   integer:: dynsize
contains
   ! Allocating inside a routine
   subroutine DynAlloc (in_howmany)
      integer, intent(in):: in_howmany
      dynsize = in_howmany
      allocate (dyna(dynsize))
   end subroutine DynAlloc

   ! Use inside a routine
   subroutine DynDump ()
      integer:: i
      do i = 1, dynsize
         print *, dyna(i)
      enddo
   end subroutine DynDump

   ! Deallocating
   subroutine DynClose
      deallocate (dyna)
   end subroutine DynClose
end module Dyn

program main
   use Dyn
   integer, parameter:: mainmax = 10
   
   ! Allocation inside
   call DynAlloc (mainmax)

   ! Usage outside
   do i = 1, mainmax
      dyna(i) = i * i
   end do

   ! Usage inside another routine
   call DynDump

   call DynClose
   stop
end
 
Thanks xwb!!! Regarding the mainmax = 10 ... is that I have to know the maximum before hand?
 
That is just for the test program.

You can work out what you want in dynalloc and allocate the array in there. No parameter will be required in that case.
 
Thanks xwb it works! I have modified it a bit and it is okay.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top