指標與結構
在 C 語言中,可以使用 **Pointer(指標)** 指向一個 `struct` 結構資料,透過指標讀取或修改結構成員。
## 基本語法
假設有結構:
```c
struct Student {
char name[20];
int age;
};
```
若宣告一個結構變數:
```c
struct Student s;
```
取得它的位址並存入指標:
```c
struct Student *p = &s;
```
透過指標存取結構成員時,可以使用:
```c
p->age
```
這等同於:
```c
(*p).age
```
其中 `->` 是專門用來透過結構指標存取成員的運算子。
## 簡單範例
```c
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int age;
};
int main(void) {
struct Student student;
struct Student *ptr;
// ptr 指向 student 的位址
ptr = &student;
// 透過指標設定結構成員
strcpy(ptr->name, "Alice");
ptr->age = 20;
// 透過指標讀取結構成員
printf("姓名:%s\n", ptr->name);
printf("年齡:%d\n", ptr->age);
// (*ptr).age 與 ptr->age 的效果相同
printf("年齡:%d\n", (*ptr).age);
return 0;
}
```
輸出結果:
```text
姓名:Alice
年齡:20
年齡:20
```
重點如下:
- `&student`:取得結構變數 `student` 的記憶體位址。
- `struct Student *ptr`:宣告一個指向 `struct Student` 的指標。
- `ptr->name`:透過指標存取 `name` 成員。
- `ptr->age`:透過指標存取或修改 `age` 成員。
- `ptr->age` 等同於 `(*ptr).age`。
相關學習地圖、教學課程
C 語言,系統程式