Just extending on the pointer discussion in the other topic, I’d like to ask you some help on my original problem. I try to store a pointer to an array in a container, and use it later to manipulate the data it points to. The first call stores the pointer in the container, the second call uses the stored pointer. Is this a valid approach, if the actual argument for the pointer in the first call (which stores it) is a section of a pointer (ptr(:,ii)
)?
module test
implicit none
type :: pointer_wrapper
real, pointer :: ptr(:) => null()
end type pointer_wrapper
contains
subroutine store_pointer(wrapper, ptr)
type(pointer_wrapper), intent(out) :: wrapper
real, pointer, intent(in) :: ptr(:)
wrapper%ptr => ptr
end subroutine store_pointer
subroutine use_pointer(wrapper)
type(pointer_wrapper), intent(inout) :: wrapper
call random_number(wrapper%ptr)
! Bug vanishes, if next line is commented out...
wrapper%ptr(:) = wrapper%ptr + 1.0
end subroutine use_pointer
end module test
program testprog
use test
implicit none
real, allocatable, target :: data(:,:)
real, pointer :: ptr(:,:)
type(pointer_wrapper) :: wrapper
integer :: ii
allocate(data(4, 8))
ptr => data(:,:)
data(:,:) = 0.0
do ii = 1, size(data, dim=2)
print *, "BEFORE ", ii, maxval(ptr(:,ii))
call store_pointer(wrapper, ptr(:,ii))
print *, "BETWEEN", ii, maxval(ptr(:,ii))
call use_pointer(wrapper)
print *, "AFTER ", ii, maxval(ptr(:,ii))
end do
end program testprog
The code can be compiled with all three compilers I have at hand. The executable does what I expect in two of the cases, but trashes the memory for one of the compilers. So I am wondering, whether it is a compiler bug, or whether the code violates the standard somehow. (Interestingly, if I turn the pointer in store_pointer
to intent(inout)
, all three compilers generate an error, telling me, that ptr(:, ii)
is not a valid pointer. So I am somewhat confused…)