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 */
}