dynamic allocation pointers


Skif
12-22-2008, 07:18 AM
Hi at all
I a problem with a fortran pointer.
I must do a dynamic vector with a pointer:

!********
subroutine pippo()
...
integer, pointer, dimension(:) :: pVec
...
stop
end
!********

if in the subroutine I dimension the vector I don't have problem

!********
subroutine pippo1()
...
integer, pointer, dimension(:) :: pVec
allocate (pippo(1))
pippo(1) = 999 !OK
...
stop
end
!********

the subroutine pippo1 is ok
but if I define the vector dimension of pVec in another sub
I a problem of access violation

!********
subroutine pippo2()
...
integer, pointer, dimension(:) :: pVec
call load(pVec)
...
stop
end

subroutine load(pVec)
implicit none
integer, pointer, dimension(:) :: pVec
allocate(pVec(1)) !ERROR
return
end
!********

do you knows how to do?
thanks!!

davekw7x
12-22-2008, 09:01 AM
I must do a dynamic vector with a pointer... how...?


From Fortran 90 Notes on Pointer Variables (http://www.pcc.qub.ac.uk/tec/courses/f77tof90/stu-notes/f90studentMIF_6.html), Section 5.6:

"If a procedure has a pointer or target dummy argument, the interface to the procedure must be explicit."


For example, using your subroutines (compiled with GNU gfortran):

! Using a pointer argument with dynamic allocation in subroutine
!
! Could use a module or can just make the interface explicit
! in the subprogram that calls the one that does the allocation
!
!
! davekw7x
!********
subroutine pippo2()

implicit none

interface ! interface block for load
subroutine load(p)
integer, dimension(:), pointer :: p
end subroutine load
end interface

integer, pointer, dimension(:) :: pVec

write(*,*) 'pippo2: Calling load'
call load(pVec)

write(*,*) 'pippo2: Back from load'
write(*,'(/" pippo2: pVec(1) = ",I0/)') pVec(1)

deallocate(pVec)

return
end

subroutine load(p)

implicit none
integer, pointer, dimension(:) :: p

write(*,*) 'load : Calling allocate'
allocate(p(1))

write(*,*) 'load : Back from allocate'

p(1) = 42

return
end
!********
program main

write(*,*) 'main : Calling pippo2'
call pippo2

write(*,*) 'main : Back from pippo2'

stop
end



Output:

main : Calling pippo2
pippo2: Calling load
load : Calling allocate
load : Back from allocate
pippo2: Back from load

pippo2: pVec(1) = 42

main : Back from pippo2


Regards,

Dave

Skif
12-22-2008, 01:28 PM
fantastic ^_^
thanks!!