目录

Fortran - 指针( Pointers)

在大多数编程语言中,指针变量存储对象的内存地址。 但是,在Fortran中,指针是一种数据对象,它具有比仅存储内存地址更多的功能。 它包含有关特定对象的更多信息,如类型,等级,范围和内存地址。

指针通过分配或指针分配与目标相关联。

声明指针变量

使用pointer属性声明指针变量。

以下示例显示了指针变量的声明 -

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

当不再需要时,应该通过deallocate语句清空分配的存储空间,并避免累积未使用和不可用的内存空间。

目标和协会

目标是另一个正常变量,为它留出空间。 必须使用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

指针可以是 -

  • Undefined
  • Associated
  • Disassociated

在上面的程序中,我们使用=“运算符将指针p1与目标t1 associated 。 相关函数测试指针的关联状态。

nullify语句将指针与目标解除关联。

Nullify不会清空目标,因为可能有多个指针指向同一目标。 但是,清空指针也意味着无效。

例子1 (Example 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
end program pointerExample

编译并执行上述代码时,会产生以下结果 -

1
1
5
5
8
8
8
T
F
T
0
0
10
10

请注意,每次运行代码时,内存地址都会有所不同。

例子2 (Example 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
↑回到顶部↑
WIKI教程 @2018