Fortran 指针
在大多数编程语言中,指针变量存储对象的内存地址。然而,在 Fortran 中,指针是一种数据对象,它的功能不仅仅是存储内存地址。它包含有关特定对象的更多信息,如类型、维度、范围和内存地址。
指针通过分配或指针赋值与目标相关联。
声明指针变量
指针变量是用指针属性声明的。
以下实例显示了指针变量的声明:
integer, pointer :: p1 ! pointer to integer
real, pointer, dimension (:) :: pra ! pointer to 1-dim real array
real, pointer, dimension (:,:) :: pra2 ! pointer to 2-dim real array
指针能够:
- 动态分配的内存区域。
- 与指针类型相同的数据对象,具有
target
属性。
为指针分配空间
allocate
语句允许您为指针对象分配空间。例如:
program pointerExample
implicit none
integer, pointer :: p1
allocate(p1)
p1 = 1
Print *, p1
p1 = p1 + 4
Print *, p1
end program pointerExample
结果为:
1
5
当不再需要分配的存储空间时,您应该通过解除分配语句将其清空,并避免累积未使用和不可用的内存空间。
目标与关联
目标是另一个普通变量,为它留出了空间。目标变量必须用 target
属性声明。
您可以使用关联运算符(=>
)将指针变量与目标变量相关联。
让我们重写前面的例子:
program pointerExample
implicit none
integer, pointer :: p1
integer, target :: t1
p1=>t1
p1 = 1
Print *, p1
Print *, t1
p1 = p1 + 4
Print *, p1
Print *, t1
t1 = 8
Print *, p1
Print *, t1
end program pointerExample
结果为:
1
1
5
5
8
8
指针可以是:
- 未定义
- 相关
- 已解除关联
在上面的程序中,我们使用 =>
运算符将指针 p1 与目标 t1 相关联。关联的函数测试指针的关联状态。
nullify
语句将指针与目标解除关联。
nullify
不会清空目标,因为可能有多个指针指向同一目标。然而,清空指针也意味着无效。
实例1
program pointerExample
implicit none
integer, pointer :: p1
integer, target :: t1
integer, target :: t2
p1=>t1
p1 = 1
Print *, p1
Print *, t1
p1 = p1 + 4
Print *, p1
Print *, t1
t1 = 8
Print *, p1
Print *, t1
nullify(p1)
Print *, t1
p1=>t2
Print *, associated(p1)
Print*, associated(p1, t1)
Print*, associated(p1, t2)
!what is the value of p1 at present
Print *, p1
Print *, t2
p1 = 10
Print *, p1
Print *, t2
结果为:
1
1
5
5
8
8
8
T
F
T
0
0
10
10
请注意,每次运行代码时,内存地址都会不同。
实例2
program pointerExample
implicit none
integer, pointer :: a, b
integer, target :: t
integer :: n
t = 1
a => t
t = 2
b => t
n = a + b
Print *, a, b, t, n
end program pointerExample
结果为:
2 2 2 4