Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Allocatable arrays in modules

Alireza_Forghani
Beginner
1,074 Views

In my code, there is a data container module that includes allocatable arrays. 

The main subroutine, calls a subroutine to initialize the arrays. Both main subroutine and initialize subroutines, use the data_container module. 

The problem is that after the arrays are initialized, the main subruotine, does not see the initialization of the array:

module data_container 
real (8), dimension (:), allocatable:: A
end module data_container 

subroutine initialize
use data_container
allocate (A(10))
end subroutine initialize

recursive subroutine main_subroutine
use data_container
call initialize

end subroutine main_subroutine


The real program is more complicated and the array is a complex data type. 

Thanks,

Alireza

0 Kudos
2 Replies
Alireza_Forghani
Beginner
1,074 Views

Sorry, my bad. I was including an older modules folder when compiling the main_subroutine code. 

 

0 Kudos
John_Campbell
New Contributor II
1,074 Views

The following modified example might demonstrate a successful allocation.

module data_container 
 integer, parameter :: dp = selected_real_kind (14)
 real (kind=dp), dimension (:), allocatable :: A
end module data_container 

subroutine initialize
use data_container

 write (*,*) '  initialise     : A is allocated = ',allocated (A)
 if ( allocated (A) ) then
   write (*,*) 'A is already allocated ??'
 else
   allocate (A(10))
 end if
 write (*,*) '  initialise     : A is allocated = ',allocated (A)
 
end subroutine initialize

recursive subroutine main_subroutine       !  why recursive ?
use data_container

 write (*,*) ' main_subroutine : A is allocated = ',allocated (A)

 call initialize

 write (*,*) ' main_subroutine : A is allocated = ',allocated (A)

end subroutine main_subroutine

Program Alloc_test
use data_container

 write (*,*) 'Alloc_test       : A is allocated = ',allocated (A)
 call main_subroutine
 write (*,*) 'Alloc_test       : A is allocated = ',allocated (A)

end

Why is main_subroutine recursive ? You don't want to use ALLOCATE if the array is already allocated.

0 Kudos
Reply