指標


指標用於指向儲存在計算機記憶體中任何位置的值的地址。獲取儲存在該位置的值稱為解除參照指標。指標提高了重複過程的效能,例如:

  • 遍歷字串
  • 查詢表
  • 控制表
  • 樹結構

指標詳細資訊

  • 指標算術:指標中有四個算術運算子:++--+-
  • 指標陣列:可以定義陣列以容納多個指標。
  • 指標的指標:C語言允許指標的指標等等。
  • 將指標傳遞給C語言的函式:通過參照或地址傳遞引數使得被呼叫函式可以在呼叫函式中更改傳遞的引數。
  • 從C語言函式返回指標:允許函式返回指向區域性變數,靜態變數和動態分配記憶體的指標。

指標範例程式

#include <stdio.h>  

int main()
{
    int a = 5;
    int *b;
    b = &a;

    printf("value of a = %d\n", a);
    printf("value of a = %d\n", *(&a));
    printf("value of a = %d\n", *b);
    printf("address of a = %u\n", &a);
    printf("address of a = %d\n", b);
    printf("address of b = %u\n", &b);
    printf("value of b = address of a = %u", b);
    system("pause");
    return 0;
}

執行上面範例程式碼,得到以下結果 -

value of a = 5
value of a = 5
value of a = 5
address of a = 13630708
address of a = 13630708
address of b = 13630696
value of b = address of a = 13630708

指標的指標範例程式

#include <stdio.h>  

int main()
{
    int a = 5;
    int *b;
    int **c;
    b = &a;
    c = &b;
    printf("value of a = %d\n", a);
    printf("value of a = %d\n", *(&a));
    printf("value of a = %d\n", *b);
    printf("value of a = %d\n", **c);
    printf("value of b = address of a = %u\n", b);
    printf("value of c = address of b = %u\n", c);
    printf("address of a = %u\n", &a);
    printf("address of a = %u\n", b);
    printf("address of a = %u\n", *c);
    printf("address of b = %u\n", &b);
    printf("address of b = %u\n", c);
    printf("address of c = %u\n", &c);
    system("pause");
    return 0;
}

執行上面範例程式碼,得到以下結果 -

value of a = 5
value of a = 5
value of a = 5
value of a = 5
value of b = address of a = 16252636
value of c = address of b = 16252624
address of a = 16252636
address of a = 16252636
address of a = 16252636
address of b = 16252624
address of b = 16252624
address of c = 16252612