# struct 指標
###### 葛家聿
###### 2017 資訊之芽 語法班
---
## 複習 - struct
- 很多資料來描述
- 可以丟進函數
```cpp
struct Food{
int price;
int taste;
};
double CP(Food somefood){
return (double)somefood.taste / somefood.price;
}
```
---
## 複習 - 指標
- 記憶體位址
- \* 取值 ←→ &取址
- 可以丟進函數
```cpp
int hp = 50, mp = 25;
int *hp_ptr = &hp; // hp_ptr == 0x69fef8
hp_ptr == &hp; // true
*hp_ptr == hp; // true
hp_ptr == &*hp_ptr; // true
hp == *&hp; // true
void drinkwater(int *mp_ptr){
*mp_ptr += 100;
}
```
---
## 組合起來
```cpp
Food hamburger = ({80, 75});
Food *lunch = &hamburger;
```
----
## 舉例來說
[視覺化教學](https://goo.gl/asmRj3)
```cpp
int main(){
Food taida_cafeteria = {50, 59};
Food taida_bakery = {30, 60};
Food macdonalds = {119, 87};
Food *myfavorite = &macdonalds;
std::cout << (*myfavorite).price << std::endl;
}
```
----
## 為什麼要這麼複雜呢?
```cpp
struct Person{
std::string name;
Person mother;
Person father;
};
int main(){
//...
std::cout << me.mother.name << std::endl;
}
```
error: field 'mother' has incomplete type 'Person'
----
## 正確的作法
```cpp
struct Person{
std::string name;
Person *mother;
Person *father;
};
int main(){
//...
std::cout << (*(*me).mother).name << std::endl;
}
```
---
## ->
每次都一堆點點星星好麻煩~
```cpp
std::cout << (*(*me).mother).name << std::endl;
std::cout << me->mother->name << std::endl;
```
---
## 例題
```cpp
資訊之芽目前有A~F 6位講師
A最好的朋友為B、B最好的朋友為C ... F最好的朋友為A
給一個"講師的指標",輸出他朋友的朋友的名字
```
- `friend` 是 C++ 的關鍵字,請不要使用
- 不能 std::cin 東西給指標
----
## 範例解
```cpp
struct Lector{
char name;
Lector *bestfriend;
};
int main(){
Lector sprout_lectors[6];
for(int i=0; i<6; i++){
sprout_lectors[i].name = 'A' + i;
sprout_lectors[i].bestfriend = &sprout_lectors[(i+1)%6];
}
Lector *ptr = /*sometesting*/;
std::cout << ptr->bestfriend->bestfriend->name << std::endl;
}
```
---
## 例題2
```
資訊之芽在學長姊的廣告下,學生人數不斷增加。
時不時就有人介紹新同學給大家認識。
```
- 要如何存下大家的資料呢?
----
# 解?
---
# 動態記憶體配置
## new / delete
----
## 解
- 每次有新同學加入時,向電腦要一些記憶體儲存
---
## new
[視覺化教學](https://goo.gl/QunxCu)
- 要一些記憶體存東西,回傳那些記憶體的位址
```cpp
struct Student{
std::string name;
Student *introducer;
};
int main(){
Student firststudent = {"Alice", NULL};
Student *thelaststudent = &firststudent, *temp;
std::string name;
while( std::cin >> name){
temp = new Student({name, thelaststudent});
thelaststudent = temp;
}
}
```
----
## new
- 一個整數
```cpp
int *ptr = new int;
```
- 一個值為520的整數
```cpp
int *ptr = new int(520);
```
- 一個長度為520的整數陣列
```cpp
int *ptr = new int[520];
```
----
## new
[最簡單的例子](https://goo.gl/78SmMb)
---
## delete
[視覺化教學](https://goo.gl/cGMe7Y)
- 給定指標,歸還他所指的那塊記憶體
```cpp
Food *lunch = new Food({30,60});
delete lunch; //eat
```
----
## delete
- 一個東西
```cpp
delete ptr;
```
- 一串東西
```cpp
delete [] ptr;
```
---
## 例題2
- 把講師變成動態加入
---
## unity 小遊戲
- disable
- distroy
{"metaMigratedAt":"2023-06-14T12:55:34.878Z","metaMigratedFrom":"Content","title":"struct 指標","breaks":true,"contributors":"[]"}