###### tags: `sprout`
# pointer
slide: https://hackmd.io/@i2y3z9dITSa_Q_7V7h-AoA/H1lPJuqc8#/
--廖凰汝--
---

----
```cpp=
int a = 10;
```
當宣告一個變數,會將他放在電腦的某一個位置

----
怎麼知道變數在電腦的位址是什麼?

----
```cpp=
#include <iostream>
int main() {
int a = 10;
std::cout<<"變數a的位址在"<<&a<<std::endl;
}
```
----
可是我想要把變數a的地址存起來!
```cpp=
int a_address = &a; // 可以用int存嗎?
double a_address = &a; // 還是double ?
// ......
// 目前知道的型態都不符合
```
----
## 指標型態 pointer
```cpp=
int *ptr = &a;
int* ptr = &a;
```
ptr: 一個指向int變數的指標
* 剛剛的例子改寫
----
注意!如果我們想宣告兩個指標變數
以下有什麼問題?
```cpp=
int* ptr1, ptr2;
// same as int* ptr1; int ptr2;
```
```cpp=
int *ptr1, *ptr2;
```
----
回到房子的例子。
當我們知道房子的位址後,就想去看看房子裡有什麼。
但,我們需要一把鑰匙。
----

```cpp=
int a = 10;
int *ptr = &a; // ptr 存變數a的位址
cout<<"a的內容是什麼?"<<*ptr;
// 用 * 打開ptr位址的變數(也就是a),看裝了什麼
```
----
\* 是取值符號
& 是取址符號

----
除了看房子裡有什麼,我還可以換房子裡的內容
```cpp=
int a = 10;
int *ptr = &a;
*ptr = 20;
// 用* 把ptr位址上的房子打開後,把他的內容換成 20
```
----
注意!
int *ptr 跟 *ptr 的 * 不一樣
int* 是型態, *ptr 是把 ptr取值出來。
---
### 陣列
> 一大排位址連續的房子
----
```cpp=
int arr[4] = {8, 7, 8, 7};
```

----
其實,arr 也代表著第一棟房子的位址
```cpp=
int arr[4] = {8, 7, 8, 7};
cout<<arr;
cout<<&arr[0];
```
----
為什麼前後位址都差4?
int 的大小?
```cpp=
sizeof(arr[0])
```
----
不小心踏入禁地?
Segmentation Fault
(oj會顯示RE runtime error 執行時發生錯誤)
----
```cpp=
int arr[2] = {1, 2};
arr[3] = 3; // segmentation fault
```
----
what's wrong with this?
```cpp=
int arr[1000];
for (int i=0; i<=1000; i++) {
arr[i] = i;
}
```
---
### 指標的運算
```cpp=
int arr[5] = {2, 4, 6, 8, 10};
cout << arr << '\n'; // address of arr[0]
cout << arr + 1 << '\n'; // address of arr[1]
cout << arr + 2 << '\n'; // address of arr[2]
cout << arr + 3 << '\n'; // address of arr[3]
cout << arr + 4 << '\n'; // address of arr[4]
```
----
```cpp=
int arr[5] = {2, 4, 6, 8, 10};
cout<<(&arr[4]-&arr[0]);
```
----
想一下,這下面的code 在做什麼?
```cpp=
int arr[4] = {1, 2, 3, 4};
for (int i=0; i<4; i++) {
cout<< *(arr+i) << endl;
}
```
----
想一下,印出的結果是什麼?
```cpp=
int arr[4] = {2, 4, 6, 8};
cout << (*arr + 2) << endl;
cout << (*(arr+2)) << endl;
```
----
小練習1
查詢某一個值有沒有在陣列中,輸出他的所在的index
若沒有,輸出Not Found
https://ideone.com/rgQo9B
----
小練習2
要輸入什麼i,才能印出You shoot the target?
https://ideone.com/41GbzY
{"metaMigratedAt":"2023-06-15T08:11:19.780Z","metaMigratedFrom":"Content","title":"pointer","breaks":true,"contributors":"[{\"id\":\"8b6cb7cf-d748-4d26-bf43-fed5ee1f80a0\",\"add\":2660,\"del\":174}]"}