On Saturday, January 6, 2018 at 12:38:45 PM UTC-5, Mohammad wrote:
> ..
>
> Yes, that's the best practice. Initialize variables (pointers) before use!
Keeping in mind the dangers associated with the standard feature that arises out of "Explicit initialization of a variable that is not in a common block implies the SAVE attribute,"
note "If null-init appears, the initial association status of the object is disassociated."
But derived type components including pointers can have explicit initialization. So you can do:
!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
program p
type dyna
integer :: dat = 0
type(dyna), pointer :: p => null()
end type dyna
! local vars
type(dyna), pointer :: head => null()
type(dyna), pointer :: tail => null()
type(dyna), pointer :: ptr => null()
integer :: i, ierr
! set data
do i=1, 5
if (.not. associated(head) ) then
allocate(head, stat=ierr)
tail => head
tail%dat = i
else
allocate(tail%p, stat=ierr)
tail => tail%p
tail%dat=i
end if
end do
! print the data
ptr => head
do
if ( .not. associated(ptr) ) exit
print*, ptr%dat
ptr => ptr%p
end do
end program p