Struct 結構
# C 語言的 `struct` 結構
`struct`(結構)可以把**不同型別的資料**組合成一個自訂型別,方便描述一個完整的物件。
例如,一位學生可能包含:
- 姓名:字元陣列
- 年齡:整數
- 成績:浮點數
這些資料可以放在同一個結構中。
---
## 1. 宣告結構
```c
struct Student {
char name[50];
int age;
float score;
};
```
這裡定義了一個名為 `Student` 的結構型別,但還沒有建立變數。
建立變數:
```c
struct Student student1;
```
---
## 2. 存取結構成員
使用小數點 `.` 存取成員:
```c
student1.age = 20;
student1.score = 85.5;
```
存取字串時,可以使用 `strcpy()`:
```c
strcpy(student1.name, "Amy");
```
需要引入:
```c
#include <string.h>
```
---
## 3. 宣告時初始化
```c
struct Student student1 = {"Amy", 20, 85.5};
```
也可以使用指定成員初始化:
```c
struct Student student2 = {
.name = "Bob",
.age = 21,
.score = 90.0
};
```
---
## 範例:建立並顯示學生資料
```c
#include <stdio.h>
struct Student {
char name[50];
int age;
float score;
};
int main(void) {
struct Student student = {"Amy", 20, 85.5};
printf("姓名:%s\n", student.name);
printf("年齡:%d\n", student.age);
printf("成績:%.1f\n", student.score);
// 修改成員
student.score = 90.0;
printf("修改後成績:%.1f\n", student.score);
return 0;
}
```
輸出可能為:
```text
姓名:Amy
年齡:20
成績:85.5
修改後成績:90.0
```
---
## 4. 使用 `typedef` 簡化寫法
一般寫法:
```c
struct Point p1;
```
可以搭配 `typedef` 簡化為:
```c
typedef struct {
int x;
int y;
} Point;
Point p1 = {10, 20};
```
之後不需要再寫 `struct`,直接使用 `Point` 即可。
---
## 常見語法整理
```c
// 定義結構
struct TypeName {
type member1;
type member2;
};
// 宣告變數
struct TypeName variable;
// 宣告並初始化
struct TypeName variable = {value1, value2};
// 存取成員
variable.member1;
```
`struct` 的主要用途是將相關資料集中管理,使程式的資料結構更清楚,也常用於陣列、函式、檔案處理及大型程式設計中。
相關學習地圖、教學課程
C 語言,系統程式