C/指標

本頁使用了標題或全文手工轉換
維基教科書,自由的教學讀本
< C

指標的定義[編輯]

  • 指標為一種變數,儲存的內容是記憶體地址。
  • 指標的使用會因為目的型態不同而有些微的影響。

變數指標[編輯]

  • 指標的宣告:
 int *ptr;  /* 則  (int *) 為變數型態,ptr 為變數名稱 */
  • 取得記憶體地址:在變數前面使用 '&' 字元。
  • 指向記憶體地址:在變數前面使用 '*' 字元。
#include <stdio.h>
int main()
{
    int v = 5;
    int *ptr = &v;
    printf("%d\n", *ptr);
}

函數指標[編輯]

函數其實也可以是指標。

#include <stdio.h>
typedef void (*MyDelegate)(int i );
MyDelegate test1( int i ) 
{
    printf("%d\n", i );
}
MyDelegate test2( int i ) 
{
    printf("%d\n", i+1 );
}

int
mainint argc, char* argv[]
{
    MyDelegate function;
    function = (MyDelegate)test1;
    function( 21 );  /* 等同於呼叫 test1 */
    function = (MyDelegate)test2;
    function( 21 );  /* 等同於呼叫 test2 */
}