2011-03-25 142 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