2011-03-25 147 views
1
#include <stdio.h> 

typedef int (*func)(int); 

int add (int a) 
{ 
     return ++a; 
} 

int getfunc(func myfunc) 
{ 
    myfunc = &add; 
    return 0; 
} 

int main() 
{ 
     int i; 
     func myfunc; 

     i = 10; 
     getfunc(myfunc); 

     printf(" a is %d\n", (*myfunc)(i)); 

     return 0; 
} 

我無法得到我想要的。 結果是「a是0」。 這是爲什麼?typedef功能指針

回答

4

我覺得你真的很幸運,你得到了a is 0而不是崩潰。問題是getfunc是通過值獲取函數指針,所以getfunc中的myfunc = &add根本不會影響調用者。嘗試

int getfunc(func *myfunc) 
{ 
    *myfunc = &add; 
    return 0; 
} 

,並在主:

getfunc(&myfunc); 
+0

謝謝你的回答 – taolinke 2011-03-25 13:09:59

1

應該更多這樣的(標記有<<<變化):

#include <stdio.h> 

typedef int (*func)(int); 

int add(int a) 
{ 
    return ++a; 
} 

func getfunc(void) // <<< 
{ 
    return &add; // <<< 
} 

int main() 
{ 
    int i; 
    func myfunc; 

    i = 10; 
    myfunc = getfunc(); // <<< 

    printf(" a is %d\n", (*myfunc)(i)); 

    return 0; 
} 
+0

謝謝,這是正確的了。 – taolinke 2011-03-25 13:11:50

2

沒有此問題,但你需要按地址傳遞,而不是價值。這個問題似乎是getfunc(myfunc);

修復getFunc到:

int getfunc(func *myfunc) 
{ 
    *myfunc = &add; 
    return 0; 
} 

getFunc(&myfunc);

+0

非常感謝。你說得對! – taolinke 2011-03-25 13:07:27

1

myfunc稱它是一個指針。你創建了它,但從來沒有給它賦值。然後你用野指針呼叫getfunc

試試這個(你的版本,簡體):

int getfunc(func *myfunc) 
{ 
    *myfunc = add; 
    return 0; 
} 

int main() 
{ 
     func myfunc = NULL; 
     getfunc(&myfunc); 
} 
+0

Thanks.Yes,創建時應指定一個指針。 – taolinke 2011-03-25 13:08:45