# 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

• 動態分配的內存區域
• 數據對象與目標屬性相同類型的指針

## 分配指針的空間

allocate語句可以分配指針對象空間。例如：

program pointerExample implicit none

integer, pointer :: p1
allocate(p1) p1 = 1 Print *, p1

p1 = p1 + 4 Print *, p1 end program pointerExample

1
5

## 目標和關聯

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

• 未定義的
• 關聯的
• 未關聯的

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
952754640
952754640
10
10

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