WeHelp
C 語言是一種通用的、程序式的程式語言,可直接對記憶體與硬體進行操作,效率極高。
  1. C 特色用途、相關職務
  2. Windows 環境建置、測試
  3. Mac 環境建置、測試
  4. Linux 環境建置、測試
  5. C 標準輸出、輸入
  6. C 資料型態
  7. C 變數使用
  8. C 運算符號
  9. IF 條件判斷
  10. Switch 條件判斷
  11. While 迴圈
  12. For 迴圈
  13. Array 陣列
  14. String 字串
  15. Function 函式
  16. 標準函式庫
  17. Struct 結構
  18. Pointer 指標
  19. 指標與函式參數
  20. 指標與陣列
  21. 指標與結構
  22. 動態配置記憶體
指標與結構
在 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 語言,系統程式
掌握基礎的 C 語法,以及進階的系統程式開發能力。