# 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`