module shared
!derived type target here
integer, parameter :: nblock = 2
integer, parameter :: xdim = 2
TYPE block_info
INTEGER :: il=10,jl=20,kl=30
REAL, ALLOCATABLE :: x(:)
END TYPE block_info
TYPE(block_info), TARGET :: block(nblock)
end module shared
module point_to
!point to subroutine here
use shared
REAL, POINTER :: x(:)
integer :: il,jl,kl
contains
subroutine set_current(n)
nullify(x)
il = block(n)%il
jl = block(n)%jl
kl = block(n)%kl
x => block(n)%x(0:xdim)
end subroutine set_current
end module point_to
program main
use shared
use point_to
!Iam allocating derived type target and initialize
do i = 1, nblock
allocate(block(i)%x(0:xdim))
do j = 0, xdim
block(i)%x(j) = dble(i)*dble(j)
enddo
enddo
!Iam pointing using set_current subroutine and print
do i = 1, nblock
call set_current(i)
do j = 0, xdim
write(*,*) "i= ",i, "j= ",j, block(i)%x(j), x(j)
enddo
enddo
end program main
對於上面的代碼,我得到以下輸出;0號指針有問題
i= 1 j= 0 0.00000000 0.00000000
i= 1 j= 1 1.00000000 0.00000000
i= 1 j= 2 2.00000000 1.00000000
i= 2 j= 0 0.00000000 0.00000000
i= 2 j= 1 2.00000000 0.00000000
i= 2 j= 2 4.00000000 2.00000000
我已經應用了x向量從1開始到xdim,我沒有錯誤。當第一個索引被選爲0時,問題就開始了。在上面的輸出中,最後兩個值必須相等。那麼問題在哪裏?
您使用過標籤[tag:fortran90]。對於Fortran問題,始終使用標籤[tag:fortran]。您可以添加另一個標籤來區分版本。 *但是,您的代碼不是Fortran 90.原始Fortran 95中甚至不允許對派生類型的可分配組件,它是Fortran 2003的一項功能。所以你的代碼是Fortran 2003. –