|
本帖最后由 navoski 于 2021-6-22 12:48 编辑
有人发文说Fortran没有指针数组的概念(http://blog.sciencenet.cn/blog-517015-679554.html),“Fortran不存在指针数组的概念,不能直接使用指针数组,必须通过一个包含指针的数据类型(如下)来定义数组,其效果等同于"指针数组"。”。
我重新码了一遍,居然可以通过。那到底是谁正确呢?还是说“Fortran不存在指针数组的概念”,是指不能采用直接指定数组大小的方式声明指针数组?我type(person), pointer :: pt(5)时,报错“!Error: Array pointer 'pt' at (1) must have a deferred shape or assumed rank”。
原码:
[Fortran] 纯文本查看 复制代码 !================== module func ===========================
module func
type person
character(len = 10) :: name
real :: height, weight
end type person
type pperson
type(person), pointer :: p
end type pperson
contains
subroutine sort(p)
implicit none
type(pperson) :: p(:)
type(pperson) :: temp
integer :: i, j, s
s = size(p, 1)
do i = 1, s-1
do j = i+1, s
if (p(i)%p%height < p(j)%p%height) then
temp = p(i)
p(i) = p(j)
p(j) = temp
end if
end do
end do
! return
end subroutine sort
end module func
!================ main program ==============================
program examSort
use func
implicit none
type(person), target :: p(5) = [person('chen', 180.0, 75.0), &
person('huang', 170.0, 65.0), &
person('liu', 175.0, 80.0), &
person('cai', 182.0, 78.0), &
person('xu', 178.0, 70.0) ]
type(pperson) :: pt(5)
integer :: i
forall (i=1:5)
pt(i)%p => p(i)
end forall
call sort(pt)
write(*, '(5(a8, f6.1, f5.1, /))') (pt(i)%p, i=1,5)
end program examSort
修改后的代码:
[Fortran] 纯文本查看 复制代码 !================== module func ===========================
module func
type person
character(len = 10) :: name
real :: height, weight
end type person
! type pperson
type(person), pointer :: p
! end type pperson
contains
subroutine sort(p)
implicit none
! type(pperson) :: p(:)
! type(pperson) :: temp
type(person), pointer :: p(:)
type(person), pointer :: temp
integer :: i, j, s
s = size(p, 1)
print *, 's', s
do i = 1, s-1
do j = i+1, s
! if (p(i)%p%height < p(j)%p%height) then
if (p(i)%height < p(j)%height) then
temp = p(i)
p(i) = p(j)
p(j) = temp
end if
end do
end do
! return
end subroutine sort
end module func
!================ main program ==============================
program examSortTestArrayPointer
use func
implicit none
type(person), target :: a(5) = [person('chen', 180.0, 75.0), &
person('huang', 170.0, 65.0), &
person('liu', 175.0, 80.0), &
person('cai', 182.0, 78.0), &
person('xu', 178.0, 70.0) ]
! type(pperson) :: pt(5)
!Error: Array pointer 'pt' at (1) must have a deferred shape or assumed rank
! type(person), pointer :: pt(5)
type(person), pointer :: pt(:)
integer :: i
! forall (i=1:5)
! pt(i) => p(i)
! end forall
pt => a
call sort(pt)
! write(*, '(5(a8, f6.1, f5.1, /))') (pt(i)%p, i=1,5)
write(*, '(5(a8, f6.1, f5.1, /))') (pt(i), i=1,5)
end program examSortTestArrayPointer
|
|