發表文章

目前顯示的是 4月, 2013的文章

C function pointer 指標函數

相當方便的指標函數,可以輕鬆的乎叫對應的function。 (C function pointer with array can make functions call easier.)  所有的function都有一個位址,例如 func1() ,呼叫時我們可以直接呼叫func1();  或是透過指標,如: int(*p)(); 先宣告一個指標,然後 p=func1; or p=&func1; 都可以,func1 與 &func1,都是func1的起始位置。  a.呼叫時 1. p(); 2. (*p)(); 都可以,此時p與*p都是func1的起始位置。  b.(*p)()不可以寫成*p(),()優先序高於*,這樣會出錯。  c. 對指標含數進行*(p+1) 之類的運算是沒意義的。 #include <stdio .h> #include<stdlib .h> typedef int (*MYFUNC)(); int func1() { printf("\n%s\n",__func__); } int func2() { printf("\n%s\n",__func__); } int func3() { printf("\n%s\n",__func__); } /* static (*funcs[3])() = { &func1, &func2, &func3}; * static (*funcs[3])() = { func1, func2, func3}; * 這三個寫法都一樣的效果,&可加可不加,都是指到同樣的位址。 */ static MYFUNC funcs[3] = { &func1, &func2, &func3}; int main(int argc, char *argv[]) { (*(funcs[atoi(argv[1])]))(); } 執行結果(result): [root@new-host-832 stanley]# ./a.out 0 func1 [root@new-host-832 stanl

C語言 enum

這在篇blog中,我將介紹一些enum的用法。 (I will show some enum type examples in C.) enum的基本語法 enum identifier { enumerator-list }  1. enum裡的識別字,會以int的型態,從0開始排列,你也可以給于數值。  2. enum也可以不宣告identifier , 如第二個enum的宣告方法, 可以減少define的使用,enumerator可以是相同的值,如範例中off跟yes都是1。  (Different constants in an enumeration may have the same value, identifier is not necessary) #include <stdio.h> typedef enum {sun, mon, tue, wed, thu, fri, sat}week_type; enum{on=0, off=1, no=0, yes=1}; main() { week_type day; day=thu; printf("\nDay=%d\n",day); printf("%d %d %d %d\n", on, off, no, yes); } 執結果(result): Day=4 0 1 0 1