Kodewick
開始學 →
指標和陣列17 / 30

C 語言指標和陣列

第 17 課,共 30 課 · 第 3 部分 · 指標 · 約 15 分鐘

陣列名就是第一個元素的位址,所以 p = a 後 p[i] 和 *(p + i) 都是 a[i];陣列傳給函式時,傳進去的其實是這個位址。

陣列的元素在記憶體裡是一個挨一個排著的。所以在 C 裡,指標和陣列是近親。大多數時候,陣列的名字就當作它第一個元素的位址來用:

main.c
1#include <stdio.h>2 3int main(void) {4    int scores[4] = {70, 85, 92, 64};5    int *p = scores;6    printf("%d\n", *p);7    printf("%d\n", p == &scores[0]);8    return 0;9}
輸出
70
1

int *p = scores; 沒寫 &,也不用寫:這裡的 scores 就是 &scores[0]。點單步,能看到 p 的箭頭指著陣列的第一個格子。

p + 1 是下一個元素

指向陣列的指標加 1,得到的是下一個元素的位址,不是下一個位元組。一個 int 佔 4 個位元組,所以位址其實大了 4;這個 C 會按指標的型別自己算。

main.c
1#include <stdio.h>2 3int main(void) {4    int scores[4] = {70, 85, 92, 64};5    int *p = scores;6    printf("%d\n", *(p + 1));7    printf("%d\n", *(p + 3));8    p = p + 2;9    printf("%d\n", *p);10    return 0;11}
輸出
85
64
92

點單步,看第 8 行:箭頭往右挪了兩格,指著 92。*(p + 1) 的括號不能少:*p + 1 是第一個元素加 1,也就是 71。

scores[0]701000
scores[1]851004
scores[2]921008
scores[3]641012
p1000

p = 1000 → *p = 70 (scores[0])

點按鈕:讓指標指向別的格子,或者通過指標改值

每個格子是一個 int,佔 4 個位元組;p + 1 指著下一個格子,位址正好大 4。點按鈕讓 p 挪一挪
猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2 3int main(void) {4    int a[4] = {5, 10, 15, 20};5    int *p = a;6    printf("%d %d\n", *(p + 2), *p + 2);7    return 0;8}

p[i] 就是 *(p + i)

在 C 裡,方括號是「先加,再順著找過去」的簡寫。a[i] 的意思就是 *(a + i)。陣列名可以這麼用,指標也可以:

寫法意思
a[0]*a
a[i]*(a + i)
&a[i]a + i
main.c
1#include <stdio.h>2 3int main(void) {4    double prices[3] = {2.50, 4.00, 1.25};5    double *p = prices;6    printf("%.2f %.2f\n", prices[2], *(prices + 2));7    printf("%.2f %.2f\n", p[1], *(p + 1));8    p[0] = 3.00;9    printf("%.2f\n", prices[0]);10    return 0;11}
輸出
1.25 1.25
4.00 4.00
3.00

所以指向陣列的指標,用起來和陣列一模一樣。下標從 0 開始,也是這個原因:下標是離開頭走幾步,第一個元素離開頭 0 步。

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

選一個填進空格,讓程式顯示 a[2],也就是 12。

1#include <stdio.h>2 3int main(void) {4    int a[3] = {4, 8, 12};5    int *p = a;6    printf("%d\n", );7    return 0;8}

用指標走陣列

不用 i 數,也可以讓指標從第一個元素走到最後一個。scores + 4 是緊跟在最後一個元素後面的位置;p 一到那裡就停,那裡的東西不能讀。

main.c
1#include <stdio.h>2 3int main(void) {4    int scores[4] = {70, 85, 92, 64};5    int total = 0;6    for (int *p = scores; p < scores + 4; p++) {7        total += *p;8    }9    printf("總分:%d\n", total);10    return 0;11}
輸出
總分:311

點單步,看 p 的箭頭每轉一圈往右挪一格,total 跟著變大。p++ 讓指標挪到下一個元素。

堆疊

scores[0]int70
scores[1]int85
scores[2]int92
scores[3]int64
—scores + 4
pint *
totalint0

p 每轉一圈往後挪一格,total 加上它指著的數;p 走到最後一格的後面,迴圈就停
猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2 3int main(void) {4    int steps[5] = {10, 20, 30, 40, 50};5    int *p = steps + 1;6    p++;7    printf("%d %d\n", *p, p[1]);8    return 0;9}
練習 1

用指標求和

讓一個指標走過 steps,把步數加起來(不要用 steps[i]),顯示 總數:25000。

要顯示
總數:25000
exercise1.c
1#include <stdio.h>2 3int main(void) {4    int steps[5] = {4000, 6000, 3000, 7000, 5000};5    int total = 0;6 7    printf("總數:%d\n", total);8    return 0;9}
輸出
點「執行」或按 Ctrl+Enter

陣列傳給函式

把陣列傳給函式,陣列並不會複製一份,函式拿到的是第一個元素的位址。所以函式能改外面的陣列;也所以作為引數,int a[] 和 int *a 是一個意思:

main.c
1#include <stdio.h>2 3void add_to_all(int *a, int count, int amount) {4    for (int i = 0; i < count; i++) {5        a[i] += amount;6    }7}8 9int main(void) {10    int prices[3] = {10, 25, 40};11    add_to_all(prices, 3, 5);12    printf("%d %d %d\n", prices[0], prices[1], prices[2]);13    return 0;14}
輸出
15 30 45

點單步:在 add_to_all 裡,a 是一條箭頭,指回 main 的陣列,變的是 main 框裡的格子。

main()

pricesint[3]10 25 40

add_to_all()

aint *
countint3
amountint5

a 是一條指回 main 的箭頭:add_to_all 裡改 a[i],變的是 main 框裡的 prices

函式只拿到一個位址,所以它不知道陣列有多長。在函數裡用 sizeof,得到的是指標的大小,不是陣列的大小:

main.c
1#include <stdio.h>2 3void show_size(int a[]) {4    printf("函數裡:%zu\n", sizeof a);5}6 7int main(void) {8    int prices[5] = {10, 25, 40, 8, 12};9    printf("main 裡:%zu\n", sizeof prices);10    show_size(prices);11    return 0;12}
輸出
main.c: In function 'show_size':
main.c:4:36: warning: 'sizeof' on array function parameter 'a' will return size of 'int *' [-Wsizeof-array-argument]
    4 |     printf("函數裡:%zu\n", sizeof a);
      |                                    ^
main.c:3:20: note: declared here
    3 | void show_size(int a[]) {
      |                ~~~~^~~
main 裡:20
函數裡:8

在 main 裡,prices 是 5 個 int,20 個位元組;在函數裡,a 是一個指標,8 個位元組。gcc 還專門給了一條警告。所以要像 add_to_all 那樣,把個數另外當引數傳進去。

單選

函式的引數寫成 int a[],在函數裡 sizeof a 得到的是什麼?

練習 2

數及格的人

count_pass 要數出 60 分及以上的有幾個,可它在函數裡用 sizeof 算個數,算錯了。改成多一個引數 count,讓程式顯示 及格:4。

要顯示
及格:4
exercise2.c
1#include <stdio.h>2 3int count_pass(int scores[]) {4    int count = sizeof scores / sizeof scores[0];5    int pass = 0;6    for (int i = 0; i < count; i++) {7        if (scores[i] >= 60) {8            pass++;9        }10    }11    return pass;12}13 14int main(void) {15    int scores[6] = {58, 72, 91, 45, 60, 83};16    printf("及格:%d\n", count_pass(scores));17    return 0;18}
輸出
點「執行」或按 Ctrl+Enter

字串為什麼不能用 == 比

字串是 char 陣列,它的名字也是第一個字元的位址。第 14 課說過要講:為什麼字都一樣,typed == saved 還是假。現在能看明白了:== 比的是兩個位址,而兩個陣列永遠在兩個不同的地方。

main.c
1#include <stdio.h>2#include <string.h>3 4int main(void) {5    char saved[] = "secret";6    char typed[] = "secret";7    char *same = saved;8    printf("typed == saved:%d\n", typed == saved);9    printf("same == saved:%d\n", same == saved);10    printf("strcmp:%d\n", strcmp(typed, saved));11    return 0;12}
輸出
typed == saved:0
same == saved:1
strcmp:0

same 和 saved 指著同一個陣列,所以相等。strcmp 順著兩個位址找過去,一個字元一個字元地比,比文字就該用它。

用指標走字串,和走陣列一樣,只是不數個數,碰到 '\0' 就停:

main.c
1#include <stdio.h>2 3int main(void) {4    char word[] = "banana";5    int count = 0;6    for (char *p = word; *p != '\0'; p++) {7        if (*p == 'a') {8            count++;9        }10    }11    printf("%d\n", count);12    return 0;13}
輸出
3
猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2#include <string.h>3 4int main(void) {5    char a[] = "hi";6    char b[] = "hi";7    printf("%d %d\n", a == b, strcmp(a, b) == 0);8    return 0;9}
練習 3

自己寫 strlen

寫一個函式 my_strlen:用指標沿著字串往後走,走到 '\0' 為止,返回走過了幾個字元。程式要顯示 8。

要顯示
8
exercise3.c
1#include <stdio.h>2 3int my_strlen(char *s) {4 5}6 7int main(void) {8    printf("%d\n", my_strlen("keyboard"));9    return 0;10}
輸出
點「執行」或按 Ctrl+Enter

這一課學會了

  • 陣列名就當作第一個元素的位址用:int *p = scores;。
  • p + 1 是下一個元素的位址;C 按型別的大小往後挪。
  • a[i] 就是 *(a + i),陣列和指標都一樣。
  • 可以用 p++ 走陣列,走到緊跟在最後面的位置就停;字串走到 '\0' 停。
  • 陣列傳給函式傳的是位址:函式能改它,但在函數裡 sizeof 得到的是指標的大小,所以個數要另外傳。
  • 兩個字串用 == 比的是位址;比文字用 strcmp。
第 17 課學完了嗎?第 17 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 18 課 · 15 分鐘指標出事C 語言指標最常見的幾種錯和怎麼避開:野指標、NULL 空指標、指標走出陣列、指向區域性變數的懸空指標,以及 const 指標。每個錯都能單步回放。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。