Reputation: 55
Because of some reason, I need to pass a Fortran pointer to a subroutine. The subroutine is inside a module and the main program uses this module to ensure explicit interface.
My question is, what attribute should I specify on the dummy argument of the subroutine in order to receive the passed-in pointer?
I tried the code below.
module aaa
contains
integer*4 function print_ptr_arr_1( ptr )
implicit none
integer*4, intent(in), pointer :: ptr(:)
print *, 'as pointer'
print *, size(ptr)
print '(10i3)', ptr
print *
end function print_ptr_arr_1
integer*4 function print_ptr_arr_2( ptr )
implicit none
integer*4, intent(in), target :: ptr(:)
print *, 'as target'
print *, size(ptr)
print '(10i3)', ptr
print *
end function print_ptr_arr_2
integer*4 function print_ptr_arr_3( ptr )
implicit none
integer*4, intent(in) :: ptr(:)
print *, 'as assumed shape array'
print *, size(ptr)
print '(10i3)', ptr
print *
end function print_ptr_arr_3
end module aaa
and
program main
use aaa
implicit none
integer*4 :: i1, ierr
integer*4, target :: arr(10)
integer*4, pointer :: ptr_arr(:)
do i1 = 1, 10
arr(i1) = i1
end do
ptr_arr => arr
ierr = print_ptr_arr_1( ptr_arr )
ierr = print_ptr_arr_2( ptr_arr )
ierr = print_ptr_arr_3( ptr_arr )
nullify( ptr_arr )
end program main
Three subroutines in module aaa show correct outputs as below.
sj2734@sonaram:~/work/practice/fortran_pointer$ ./a.out
as pointer
10
1 2 3 4 5 6 7 8 9 10
as target
10
1 2 3 4 5 6 7 8 9 10
as assumed shape array
10
1 2 3 4 5 6 7 8 9 10
sj2734@sonaram:~/work/practice/fortran_pointer$
What is correct and what are not? Or, are these all correct?
Upvotes: 2
Views: 2308
Reputation: 954
It depends on how you're going to use what you're passing to the function. Do you need it to be a pointer? Then give it the pointer
attribute. Do you need to point to it with another pointer in the function? Then, give it the target
attribute. The dummy argument will take on whatever attributes you give it.
If you declare it as a pointer
then you can use it as a pointer and allocate/point to new things within the function.
If you declare it as a target
then other pointers within the function could point to it, but you wouldn't be able to point to a target
with it since it's not a pointer.
If you just want to treat it as an array then you can just declare it as an assumed-size array and treat it like a regular array, but again you won't be able to use it in the same way as if it had the pointer
or target
attribute.
So they're all right, in a way. It depends on context. However, unless you really need it to be a pointer or target for a specific reason, and you're just treating it as an array then you're best off declaring it to be an assumed-size-array to avoid potential memory issues.
Upvotes: 2