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