Kodewick
開始學 →
結構體指標24 / 30

C 語言結構體指標

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

通過指標訪問結構體成員用箭頭 ->:p->score 等於 (*p).score;把結構體指標傳給函式,函式就能修改原來的結構體。

上一課說到,結構體傳給函式傳的是副本,改不了外面的。第 16 課我們用指標解決過同樣的問題:把位址交給函式。結構體也一樣,先看看指向結構體的指標:

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 = { "小林", 80 };10    struct student *p = &s;11    (*p).score = 90;12    printf("%s:%d 分\n", (*p).name, s.score);13    return 0;14}
輸出
小林:90 分

struct student *p 是一個指標,指向一個 struct student。*p 就是 s 本身,所以 (*p).score = 90 改的就是 s.score。點單步看看:p 是一個小格,一個箭頭從它指到 s 的大框上。

單選

struct student *p = &s; 之後,*p 是什麼?

箭頭 ->

這一關學一個專門的寫法:箭頭 ->。通過指標拿結構體的成員,本來要寫 (*p).score,意思是「先順著 p 找到結構體,再拿它的 score」。裡面的括號不能省:點號 . 比 * 先算,不加括號,*p.score 就成了「先拿 p 的成員 score」,可 p 是個指標,沒有成員:

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 = { "小林", 80 };10    struct student *p = &s;11    *p.score = 90;12    printf("%d\n", s.score);13    return 0;14}
輸出
main.c: In function 'main':
main.c:11:7: error: 'p' is a pointer; did you mean to use '->'?
   11 |     *p.score = 90;
      |       ^
      |       ->

編譯器都猜到你想幹什麼了:did you mean to use '->'?。每次寫 (*p). 太麻煩,所以 C 有一個專門的寫法,箭頭 ->:p->score 和 (*p).score 完全一樣。

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 = { "小林", 80 };10    struct student *p = &s;11    p->score = 90;12    p->score += 5;13    printf("%s:%d 分\n", p->name, p->score);14    return 0;15}
輸出
小林:95 分

記法很簡單:手裡是結構體,用 .;手裡是指向結構體的指標,用 ->。

手裡是結構體s.ys 就是那個結構體
手裡是指標p->y和 (*p).y 完全一樣
看手裡拿的是什麼:是結構體就用點,是指標就用箭頭
填空點一個填進空格,再點空格可以拿回來

p 指向 a。選一個符號填進空格,通過 p 把 a.y 改成 10。

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

換成箭頭

這段程式編譯不過。把 p 後面的點號都改成箭頭,讓它顯示 檯燈 89.00。

要顯示
檯燈 89.00
exercise1.c
1#include <stdio.h>2 3struct product {4    char name[20];5    double price;6};7 8int main(void) {9    struct product item = { "檯燈", 99.0 };10    struct product *p = &item;11    p.price = p.price - 10;12    printf("%s %.2f\n", p.name, p.price);13    return 0;14}
輸出
點「執行」或按 Ctrl+Enter

函式通過指標改結構體

上一課的 deposit 存不進錢,因為它拿到的是副本。把引數改成指標,呼叫時傳位址 &acc,函式就能直接改 main 裡的那個:

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}11 12int main(void) {13    struct account acc = { "小林", 100 };14    deposit(&acc, 50);15    deposit(&acc, 30);16    printf("%s的餘額:%d\n", acc.owner, acc.balance);17    return 0;18}
輸出
小林的餘額:180

點單步,走進 deposit:它的堆疊幀裡不再有一份完整的副本,只有一個指標 a,箭頭指回 main 堆疊幀裡的 acc。a->balance += amount 改的就是那邊的數。傳指標還有一個好處:不管結構體多大,複製的只是一個位址。

main()

accstruct account"小林" 100

deposit()

astruct account *
amountint50

a 裡只有 acc 的位址:a->balance 順著箭頭,改的是 main 裡的 acc

小技巧: 函式只讀不改時,引數寫成 const struct account *a。這樣既不用複製,函數裡不小心改了它,編譯器也會報錯。

單選

一個函式要改呼叫者手裡的結構體 acc,哪種寫法對?

練習 2

加分

寫函式 add_points,引數是指向 struct player 的指標和要加的分數,把分數加到這個選手身上。程式要顯示 小周:35 分。

要顯示
小周:35 分
exercise2.c
1#include <stdio.h>2 3struct player {4    char name[20];5    int points;6};7 8// 在這裡寫 add_points9 10int main(void) {11    struct player pl = { "小周", 20 };12    add_points(&pl, 10);13    add_points(&pl, 5);14    printf("%s:%d 分\n", pl.name, pl.points);15    return 0;16}
輸出
點「執行」或按 Ctrl+Enter

指向數組裡的一個

指標也可以指向結構體數組裡的某一個元素:&group[2] 就是第三個學生的位址。通過這個指標改,改的就是數組裡的那個學生,不是副本:

main.c
1#include <stdio.h>2 3struct student {4    char name[20];5    int score;6};7 8int main(void) {9    struct student group[3] = { { "小林", 82 }, { "小周", 91 }, { "小陳", 77 } };10    struct student *p = &group[2];11    printf("%s:%d 分\n", p->name, p->score);12    p->score += 10;13    printf("group[2].score = %d\n", group[2].score);14    return 0;15}
輸出
小陳:77 分
group[2].score = 87

p 指著 group[2],p->score += 10 改的就是它。函式也常這樣做:在數組裡找到一個元素,把它的位址返回來,呼叫的人拿著這個位址,直接改數組裡的那一個。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2 3struct student {4    char name[20];5    int score;6};7 8struct student *top(struct student list[], int n) {9    struct student *best = &list[0];10    for (int i = 1; i < n; i++) {11        if (list[i].score > best->score) {12            best = &list[i];13        }14    }15    return best;16}17 18int main(void) {19    struct student group[3] = { { "小林", 82 }, { "小周", 91 }, { "小陳", 77 } };20    struct student *p = top(group, 3);21    p->score = 100;22    printf("%d\n", group[1].score);23    return 0;24}

在堆上建一個結構體

結構體也能放在堆上(第 19、20 課):malloc(sizeof(struct product)) 要一塊正好放得下一個結構體的記憶體,拿到的是指向它的指標,所以接下來都用 ->:

main.c
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5struct product {6    char name[20];7    double price;8};9 10int main(void) {11    struct product *p = malloc(sizeof(struct product));12    if (p == NULL) {13        printf("記憶體不夠\n");14        return 1;15    }16    strcpy(p->name, "保溫杯");17    p->price = 59.0;18    printf("%s %.2f\n", p->name, p->price);19    free(p);20    return 0;21}
輸出
保溫杯 59.00

點單步,看堆上出現一個框,裡面是 name 和 price,main 裡的 p 用箭頭指著它;free(p) 之後,這個框變成灰色虛線,標著「已釋放」:這塊記憶體已經還回去了。

單選

p 是 malloc(sizeof(struct product)) 拿到的指標。怎麼設這件商品的價格?

練習 3

堆上的一本書

用 malloc 在堆上建一個 struct book,書名設成 "活著",頁數設成 191,顯示 活著:191 頁,最後 free 掉。

要顯示
活著:191 頁
exercise3.c
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5struct book {6    char title[20];7    int pages;8};9 10int main(void) {11 12    return 0;13}
輸出
點「執行」或按 Ctrl+Enter

函式建,呼叫的人還

在堆上建結構體,常常寫成一個函式:它要記憶體、填好成員、把指標交回來。堆上的東西函式結束後還在,所以這樣做沒問題(如果返回的是區域性變數的位址就不行了,第 18 課)。代價是:呼叫的人用完要記得 free。引數 const char *name 是函式接收一個只讀字串的常見寫法:傳進來的是第一個字元的位址(第 17 課),const(第 18 課)表示函式不會改它。

main.c
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5struct product {6    char name[20];7    double price;8};9 10struct product *new_product(const char *name, double price) {11    struct product *p = malloc(sizeof(struct product));12    if (p != NULL) {13        strcpy(p->name, name);14        p->price = price;15    }16    return p;17}18 19int main(void) {20    struct product *a = new_product("保溫杯", 59.0);21    struct product *b = new_product("雨傘", 35.5);22    if (a == NULL || b == NULL) {23        return 1;24    }25    printf("%s %.2f\n", a->name, a->price);26    printf("%s %.2f\n", b->name, b->price);27    printf("一共 %.2f\n", a->price + b->price);28    free(a);29    free(b);30    return 0;31}
輸出
保溫杯 59.00
雨傘 35.50
一共 94.50
單選

new_product 在堆上建好結構體,把指標交回來。這塊記憶體什麼時候還回去?

free 以後別再用

這一關講結構體指標最常見的一個錯:free 之後又去用它。那塊記憶體已經還回去了,p 卻還指著那裡:

main.c
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5struct product {6    char name[20];7    double price;8};9 10int main(void) {11    struct product *p = malloc(sizeof(struct product));12    if (p == NULL) {13        return 1;14    }15    strcpy(p->name, "雨傘");16    p->price = 35.5;17    free(p);18    printf("%s %.2f\n", p->name, p->price);19    return 0;20}
輸出
heap-use-after-free

發生了什麼: 停在第 18 行:這塊記憶體已經 free 了(還回去了),不能再用。

真正的 C 不一定會出事,可能還顯示原來的值,也可能顯示亂七八糟的東西。我們的引擎在這一行停下來。點「看看是怎麼出錯的」,看 free 之後那個框已經變灰,p 的箭頭變成了紅色虛線。

堆疊

pstruct product *

堆

"雨傘" 35.5struct product

free(p) 以後,p 裡還是原來的位址,箭頭指著的卻是已經還回去的記憶體
單選猜錯也沒關係

這段程式會怎樣?(可以點執行看看)

1#include <stdio.h>2#include <stdlib.h>3 4struct product {5    double price;6};7 8int main(void) {9    struct product *p = malloc(sizeof(struct product));10    if (p == NULL) {11        return 1;12    }13    p->price = 9.5;14    free(p);15    printf("%.1f\n", p->price);16    return 0;17}

指標是 NULL 的時候

這一關講另一個常見的錯:指標是 NULL,卻用 -> 去拿成員。比如一個函式找不到東西時返回 NULL,呼叫的人又忘了檢查,就會這樣。這個例子直接把 p 設成 NULL:

main.c
1#include <stdio.h>2#include <string.h>3 4struct student {5    char name[20];6    int score;7};8 9int main(void) {10    struct student *p = NULL;11    strcpy(p->name, "小林");12    printf("結束\n");13    return 0;14}
輸出
store to null pointer

發生了什麼: 停在第 11 行:這個指標是 NULL(空指標),不能通過它讀寫。

NULL 不指向任何東西,p->name 沒地方可去。在真正的電腦上,這樣的程式一般會直接崩潰。用 -> 之前,只要指標可能是 NULL,就先 if (p != NULL)。

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

p 可能是 NULL。選一個符號填進空格,讓程式只在 p 真的指著一個點時才去拿 p->x。

1#include <stdio.h>2 3struct point {4    int x;5    int y;6};7 8int main(void) {9    struct point *p = NULL;10    if (p  NULL) {11        printf("%d\n", p->x);12    } else {13        printf("沒有點\n");14    }15    return 0;16}

這一課學會了

  • struct student *p = &s; 是指向結構體的指標,*p 就是 s。
  • p->score 就是 (*p).score:手裡是結構體用 .,是指標用 ->。
  • 函式引數寫成結構體指標、呼叫時傳 &acc,函式就能改外面的結構體,也省得複製。
  • 函式可以返回數組裡某個元素的位址,通過它改的就是數組裡的那一個。
  • malloc(sizeof(struct product)) 在堆上建結構體;可以寫一個函式建好再返回指標,呼叫的人用完要 free。
  • free 之後別再用;指標可能是 NULL 時,先檢查再用 ->。
第 24 課學完了嗎?第 24 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 25 課 · 15 分鐘typedef 和 enum學 C 語言 typedef 和 enum:用 typedef 給型別起別名、typedef struct 省掉 struct、用 enum 給一組整數起名字,以及 switch 配 enum。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。