Kodewick
開始學 →
結構體23 / 30

C 語言結構體

第 23 課,共 30 課 · 第 5 部分 · 自己的型別 · 約 15 分鐘

結構體(struct)把幾個不同型別的成員放在一起,比如學生的姓名和分數;用 . 訪問成員,結構體賦值會複製全部成員。

一個學生有名字,也有分數。到現在為止,我們只能用兩個變數分開存:name 一個,score 一個。學生一多,就要兩個陣列,還得小心讓它們一一對上。結構體(struct)把幾樣相關的資料裝進一個變數裡:

main.c
1#include <stdio.h>2 3struct student {4    char name[20];5    int score;6};7 8int main(void) {9    struct student s = { "小林", 95 };10    printf("%s:%d 分\n", s.name, s.score);11    return 0;12}
輸出
小林:95 分

點單步看看:s 在記憶體裡畫成一個大框,裡面是 name 和 score 兩個小格。它們是一個變數的兩個部分,總是在一起。

一個結構體變數像一個大盒子,裡面按順序裝著它的成員;用 . 取出其中一格

定義一個結構體

struct student { char name[20]; int score; }; 定義了一種新的型別,說明這種變數裡有什麼。裡面的每一項叫成員:

部分在 struct student 裡是什麼
關鍵字struct說明後面定義的是一個結構體
名字student這種結構體叫什麼,用的時候寫 struct student
成員char name[20]; int score;每一項都寫型別和名字,和宣告變數一樣
結尾};花括號後面要有分號,很容易忘

定義只是說明「長什麼樣」,不佔記憶體;寫 struct student s; 才真的有了一個變數。用點號 . 拿到它的成員,讀寫都行。成員可以一項一項地賦值,字串成員用 strcpy(第 14 課):

main.c
1#include <stdio.h>2#include <string.h>3 4struct product {5    char name[20];6    double price;7    int stock;8};9 10int main(void) {11    struct product p;12    strcpy(p.name, "筆記本");13    p.price = 12.5;14    p.stock = 40;15    p.stock = p.stock - 3;16    printf("%s %.2f 元,還剩 %d 本\n", p.name, p.price, p.stock);17    return 0;18}
輸出
筆記本 12.50 元,還剩 37 本

p.stock 用起來就是一個普通的 int:可以賦值、可以參加運算。

填空點一個填進空格,再點空格可以拿回來

選一個符號填進空格,讓程式顯示 p 的成員 y,也就是 4。

1#include <stdio.h>2 3struct point {4    int x;5    int y;6};7 8int main(void) {9    struct point p = { 3, 4 };10    printf("%d\n", py);11    return 0;12}
練習 1

一本書

定義 struct book,成員是書名 title(char 陣列,20 個位元組)和頁數 pages(int)。宣告一本書 { "三體", 302 },顯示 三體:302 頁。

要顯示
三體:302 頁
exercise1.c
1#include <stdio.h>2 3// 在這裡定義 struct book4 5int main(void) {6 7    return 0;8}
輸出
點「執行」或按 Ctrl+Enter

初始化

宣告時可以用花括號一次給全:值按成員定義的順序一個對一個。給的值不夠,剩下的成員是 0(字串就是空的):

main.c
1#include <stdio.h>2 3struct product {4    char name[20];5    double price;6    int stock;7};8 9int main(void) {10    struct product a = { "鉛筆", 1.5, 120 };11    struct product b = { "橡皮", 2.0 };12    printf("%s %.2f %d\n", a.name, a.price, a.stock);13    printf("%s %.2f %d\n", b.name, b.price, b.stock);14    return 0;15}
輸出
鉛筆 1.50 120
橡皮 2.00 0

順序很要緊:寫成 { 1.5, "鉛筆", 120 } 就對不上了,編譯器會報錯或者給警告。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2 3struct point {4    int x;5    int y;6};7 8int main(void) {9    struct point p = { 5 };10    printf("%d %d\n", p.x, p.y);11    return 0;12}

賦值是複製

陣列不能用 = 整個賦值,結構體可以。b = a; 把 a 的每個成員都複製給 b,連裡面的字元陣列也一起復制。複製完它們就是兩個互不相干的變數:

main.c
1#include <stdio.h>2 3struct point {4    int x;5    int y;6};7 8int main(void) {9    struct point a = { 1, 2 };10    struct point b = a;11    b.x = 9;12    printf("a: %d %d\n", a.x, a.y);13    printf("b: %d %d\n", b.x, b.y);14    return 0;15}
輸出
a: 1 2
b: 9 2

b = a 之後,b 是一份副本:改 b.x 只動了 b,a 還是 1 2。點單步,能看到記憶體裡是兩個分開的框。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2 3struct student {4    char name[20];5    int score;6};7 8int main(void) {9    struct student a = { "小林", 80 };10    struct student b = a;11    b.score = 100;12    printf("%d %d\n", a.score, b.score);13    return 0;14}

可是兩個結構體不能用 == 比較,編譯器不認:

main.c
1#include <stdio.h>2 3struct point {4    int x;5    int y;6};7 8int main(void) {9    struct point a = { 1, 2 };10    struct point b = { 1, 2 };11    if (a == b) {12        printf("一樣\n");13    }14    return 0;15}
輸出
main.c: In function 'main':
main.c:11:11: error: invalid operands to binary == (have 'struct point' and 'struct point')
   11 |     if (a == b) {
      |           ^~

要比,就一個成員一個成員地比:a.x == b.x && a.y == b.y。

單選

a 和 b 是兩個 struct point,怎麼判斷它們一樣?

結構體陣列

結構體也能放進陣列。songs[i] 是一首歌,songs[i].seconds 是這首歌的秒數。一個歌單:

main.c
1#include <stdio.h>2 3struct song {4    char title[30];5    int seconds;6};7 8int main(void) {9    struct song songs[3] = {10        { "清晨", 269 },11        { "海邊", 226 },12        { "回家的路", 223 }13    };14    int total = 0;15    for (int i = 0; i < 3; i++) {16        printf("%d. %s(%d:%02d)\n", i + 1, songs[i].title, songs[i].seconds / 60, songs[i].seconds % 60);17        total += songs[i].seconds;18    }19    printf("一共 %d 分 %d 秒\n", total / 60, total % 60);20    return 0;21}
輸出
1. 清晨(4:29)
2. 海邊(3:46)
3. 回家的路(3:43)
一共 11 分 58 秒

每首歌的名字和長度放在一起,不會對錯行。%02d 讓秒數不夠兩位時前面補 0,4:05 不會顯示成 4:5。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2 3struct point {4    int x;5    int y;6};7 8int main(void) {9    struct point pts[3] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };10    printf("%d\n", pts[1].y);11    return 0;12}
練習 2

最便宜的

在 items 裡找出價格最低的商品,顯示 最便宜:牙刷 3.50。

要顯示
最便宜:牙刷 3.50
exercise2.c
1#include <stdio.h>2 3struct product {4    char name[20];5    double price;6};7 8int main(void) {9    struct product items[4] = {10        { "牙膏", 8.90 },11        { "毛巾", 12.00 },12        { "牙刷", 3.50 },13        { "香皂", 4.20 }14    };15 16    return 0;17}
輸出
點「執行」或按 Ctrl+Enter

傳給函式

結構體可以當引數。和 int 一樣,傳的是值:引數是一份完整的副本(第 8 課)。所以函數裡改它,外面看不到:

main.c
1#include <stdio.h>2 3struct account {4    char owner[20];5    int balance;6};7 8void deposit(struct account a, int amount) {9    a.balance += amount;10    printf("函數裡:%d\n", a.balance);11}12 13int main(void) {14    struct account acc = { "小林", 100 };15    deposit(acc, 50);16    printf("main 裡:%d\n", acc.balance);17    return 0;18}
輸出
函數裡:150
main 裡:100

點單步,走進 deposit 時,它的堆疊幀裡多出一個完整的 a:owner 和 balance 都複製過去了。變的是這個副本,函式結束它就沒了。

一個辦法是讓函式把改好的結構體返回來,由呼叫的地方存回去:

main.c
1#include <stdio.h>2 3struct account {4    char owner[20];5    int balance;6};7 8struct account deposit(struct account a, int amount) {9    a.balance += amount;10    return a;11}12 13int main(void) {14    struct account acc = { "小林", 100 };15    acc = deposit(acc, 50);16    printf("%s的餘額:%d\n", acc.owner, acc.balance);17    return 0;18}
輸出
小林的餘額:150

小技巧: 結構體大了,每次呼叫都複製一遍很浪費。更常見的辦法是傳它的位址,函式通過指標直接改,下一課就講。

練習 3

沒打上折

half_price 想把價格減半,可顯示的還是原價。改好它:讓函式返回改好的商品,main 把它存回 p。程式要顯示 毛巾 6.00。

要顯示
毛巾 6.00
exercise3.c
1#include <stdio.h>2 3struct product {4    char name[20];5    double price;6};7 8void half_price(struct product p) {9    p.price = p.price / 2;10}11 12int main(void) {13    struct product p = { "毛巾", 12.00 };14    half_price(p);15    printf("%s %.2f\n", p.name, p.price);16    return 0;17}
輸出
點「執行」或按 Ctrl+Enter

這一課學會了

  • struct 名字 { 成員; ... }; 定義一種新型別,把幾樣相關的資料放在一起;結尾要分號。
  • 宣告時用 { ... } 按順序初始化,沒給的成員是 0;也可以一項一項賦值,字串成員用 strcpy。
  • 用點號 . 讀寫成員,s.score 用起來就是一個普通變數。
  • b = a; 複製整個結構體,之後兩個互不相干;結構體不能用 == 比較。
  • 結構體陣列把一組記錄放在一起:songs[i].title。
  • 結構體傳給函式傳的是副本;要改外面的,就把新的結構體返回來(或者傳指標,下一課講)。
第 23 課學完了嗎?第 23 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 24 課 · 15 分鐘結構體指標學 C 語言結構體指標:指向結構體的指標、箭頭 ->、函式通過指標改結構體、在堆上用 malloc 建結構體、用完 free,以及用了已經 free 的結構體會怎樣。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。