Kenneth_Smith
Joined: 18 May 2012 Posts: 813 Location: Hamilton, Lanarkshire, Scotland.
|
Posted: Sat May 17, 2025 11:07 am Post subject: Module protected pointer |
|
|
Often I have an array passed as a dummy argument to a procedure in a module. In order to make that array available to all other procedures in the module a local copy is made as a module variable. This doubles the memory allocation.
For large arrays associating a pointer to the input array would avoid this extra memory allocation. I have been experimenting with this alternative to try and understand the potential pitfalls. This has revealed an issue with module protected pointers.
In the following code since the shared_array has the protected attribute the assigment shared_array(5) = 100 in the main program should generate a compiler error.
Rather a "twisted" example, since only the subroutines load_array and use_array need to be public in my_mod, in which case FTN95 would correctly reject the code.
Code: | module my_mod
implicit none
real, pointer, protected :: shared_array(:)
! real, pointer, private :: shared_array(:) ! This would be better in this context.
contains
subroutine load_array(arr)
real, target, intent(in) :: arr(:)
shared_array => arr ! associate pointer to input array
!shared_array(5) = 100 ! this assigment would correctly change arr despite its intent(in)
end subroutine load_array
subroutine use_array()
print *, shared_array
end subroutine use_array
end module my_mod
program p
use my_mod
implicit none
real :: a(5) = [1,2,3,4,5]
call load_array(a)
call use_array() ! Prints 1,2,3,4,5 via pointer association
shared_array(5) = 100 ! Since shared_array is protected, FTN95 should
! not permit this assignment (since it's external
! to MY_MOD).
print*
call use_array() ! Prints 1,2,3,4,100 due to line above being permitted.
end program p |
|
|