C 語言結構體指標
通過指標訪問結構體成員用箭頭 ->:p->score 等於 (*p).score;把結構體指標傳給函式,函式就能修改原來的結構體。
上一課說到,結構體傳給函式傳的是副本,改不了外面的。第 16 課我們用指標解決過同樣的問題:把位址交給函式。結構體也一樣,先看看指向結構體的指標:
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 存著 s 的位址,*p 順著位址找到的就是 s 本身。所以 (*p).score = 90 改的就是 s.score。箭頭 ->
這一關學一個專門的寫法:箭頭 ->。通過指標拿結構體的成員,本來要寫 (*p).score,意思是「先順著 p 找到結構體,再拿它的 score」。裡面的括號不能省:點號 . 比 * 先算,不加括號,*p.score 就成了「先拿 p 的成員 score」,可 p 是個指標,沒有成員:
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 完全一樣。
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}
p 是指向結構體的指標,拿成員用箭頭:p->y 就是 (*p).y,也就是 a.y。換成箭頭
✓這段程式編譯不過。把 p 後面的點號都改成箭頭,讓它顯示 檯燈 89.00。
檯燈 89.00
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}
函式通過指標改結構體
上一課的 deposit 存不進錢,因為它拿到的是副本。把引數改成指標,呼叫時傳位址 &acc,函式就能直接改 main 裡的那個:
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"小林" 100deposit()
astruct account *amountint50小技巧: 函式只讀不改時,引數寫成 const struct account *a。這樣既不用複製,函數裡不小心改了它,編譯器也會報錯。
一個函式要改呼叫者手裡的結構體 acc,哪種寫法對?
&acc,函數裡的 a->... 改的才是外面的 acc。直接傳 acc,函式拿到的只是一份副本;把結構體交給要指標的引數,編譯器會報錯。加分
✓寫函式 add_points,引數是指向 struct player 的指標和要加的分數,把分數加到這個選手身上。程式要顯示 小周:35 分。
小周:35 分
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}
指向數組裡的一個
指標也可以指向結構體數組裡的某一個元素:&group[2] 就是第三個學生的位址。通過這個指標改,改的就是數組裡的那個學生,不是副本:
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}
top 返回的是 &list[1],也就是 group[1] 的位址,不是副本。p->score = 100 改的就是 group[1]。返回陣列元素的位址沒問題:陣列在 main 裡,函式結束後它還在。在堆上建一個結構體
結構體也能放在堆上(第 19、20 課):malloc(sizeof(struct product)) 要一塊正好放得下一個結構體的記憶體,拿到的是指向它的指標,所以接下來都用 ->:
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)) 拿到的指標。怎麼設這件商品的價格?
p 找到它,所以用箭頭 ->。堆上的一本書
✓用 malloc 在堆上建一個 struct book,書名設成 "活著",頁數設成 191,顯示 活著:191 頁,最後 free 掉。
活著:191 頁
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}
函式建,呼叫的人還
在堆上建結構體,常常寫成一個函式:它要記憶體、填好成員、把指標交回來。堆上的東西函式結束後還在,所以這樣做沒問題(如果返回的是區域性變數的位址就不行了,第 18 課)。代價是:呼叫的人用完要記得 free。引數 const char *name 是函式接收一個只讀字串的常見寫法:傳進來的是第一個字元的位址(第 17 課),const(第 18 課)表示函式不會改它。
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;忘了就是記憶體洩漏(第 21 課)。free 以後別再用
這一關講結構體指標最常見的一個錯:free 之後又去用它。那塊記憶體已經還回去了,p 卻還指著那裡:
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 *堆
這段程式會怎樣?(可以點執行看看)
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}
free(p) 之後,那塊記憶體已經不歸你了。在普通電腦上,它可能還顯示 9.5,也可能顯示別的數,甚至崩潰;這裡的引擎會停在這一行告訴你。習慣上,free 完馬上寫 p = NULL;,提醒自己別再用它。指標是 NULL 的時候
這一關講另一個常見的錯:指標是 NULL,卻用 -> 去拿成員。比如一個函式找不到東西時返回 NULL,呼叫的人又忘了檢查,就會這樣。這個例子直接把 p 設成 NULL:
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}
p != NULL 成立,才說明 p 指著一個真的點,這時才能用 ->。這裡 p 是 NULL,所以走 else。這一課學會了
struct student *p = &s;是指向結構體的指標,*p就是s。p->score就是(*p).score:手裡是結構體用.,是指標用->。- 函式引數寫成結構體指標、呼叫時傳
&acc,函式就能改外面的結構體,也省得複製。 - 函式可以返回數組裡某個元素的位址,通過它改的就是數組裡的那一個。
malloc(sizeof(struct product))在堆上建結構體;可以寫一個函式建好再返回指標,呼叫的人用完要free。free之後別再用;指標可能是NULL時,先檢查再用->。