Reputation: 417
I'am trying to write a procedure, which store addresses of user arrays for further processing. Problem is encapsulated in this test program:
program test_ptr
real(4), target, allocatable :: i4(:,:)
real(8), target, allocatable :: i8(:,:)
real(4), pointer :: p(:,:)
allocate(i4(2,2))
allocate(i8(2,2))
p => i4 ! ok
p => i8 ! compile error
end
The compiler suggests making different pointers for different types. But I don't want to create separate pointers for real(4) and real(8). I'am trying to make generic and compact solution and have one pointer for different types of data. Is it possible?
Upvotes: 1
Views: 638
Reputation: 60008
If you really want to store adresses I would be careful with polymorphism. Pointers to polymorphic variables often point to a descriptor which has different address than the real data. Consider using type(c_ptr)
defined in the iso_c_binding
module and the function c_loc()
to obtain the address. It doesn't have to be used only for interfacing to C, there are couple of places where it is handy in pure Fortran.
Upvotes: 2
Reputation: 32366
It is possible to do this using (unlimited) polymorphism for p
.
program test_ptr
implicit none
real(kind(0.)), target :: r4(2,2)
real(kind(0d0)), target :: r8(2,2)
class(*), pointer :: p(:,:)
! some assignments, etc.
if (...some crazy condition...) then
p => r4
else
p => r8
end if
select type (p)
type is (real(kind(0.)))
print *, p
type is (real(kind(0d0)))
print *, p
end select
end program
Pay particular attention to the select type
for when later using p
.
Upvotes: 5