passing allocatable arrays to subroutines
passing allocatable arrays to subroutines
(OP)
I am trying to pass allocatable arrays declared on the main program to a subroutine and use this data inside the subroutine and then send it back to the main program. How do I declare the arrays inside the subroutine?
RE: passing allocatable arrays to subroutines
module numz
integer, parameter:: b8 = selected_real_kind(14)
integer gene_size,num_genes
integer,allocatable :: a_gene(:),many_genes(:,:)
end module
program darwin
use numz
implicit none
integer ierr
call set_size()
allocate(a_gene(gene_size),stat=ierr) !stat= allows for an error code return
if(ierr /= 0)write(*,*)"allocation error" ! /= is .ne.
allocate(many_genes(gene_size,num_genes),stat=ierr) !2d array
if(ierr /= 0)write(*,*)"allocation error"
write(*,*)lbound(a_gene),ubound(a_gene) ! get lower and upper bound
! for the array
write(*,*)size(many_genes),size(many_genes,1) !get total size and size
!along 1st dimension
deallocate(many_genes) ! free the space for the array and matrix
deallocate(a_gene)
allocate(a_gene(0:gene_size)) ! now allocate starting at 0 instead of 1
write(*,*)allocated(many_genes),allocated(a_gene) ! shows if allocated
write(*,*)lbound(a_gene),ubound(a_gene)
end program
subroutine set_size
use numz
write(*,*)'enter gene size:'
read(*,*)gene_size
write(*,*)'enter number of genes:'
read(*,*)num_genes
end subroutine set_size
RE: passing allocatable arrays to subroutines
CODE
contains
subroutine BoxCreate (blist, bsize)
! Declare an allocatable parameter
integer, allocatable, intent (inout) :: blist(:)
integer, intent (in) :: bsize
integer :: b
allocate (blist(bsize))
do b = 1, bsize
blist(b) = 0
enddo
return
end subroutine BoxCreate
subroutine BoxDelete (blist)
integer, allocatable, intent (inout) :: blist(:)
deallocate (blist)
return
end subroutine BoxDelete
end module BoxMod
program main
use BoxMod
integer, dimension(:), allocatable :: alist
integer:: amaxi
parameter (amaxi = 20)
call BoxCreate (alist, amaxi)
do i = 1, amaxi, 1
alist(i) = i * i
enddo
do i = 1, amaxi, 1
write (*,*) alist(i)
enddo
call BoxDelete (alist)
stop
end program main
RE: passing allocatable arrays to subroutines
Dan
www.dtware.com