函数指针的传递问题

来源:互联网 发布:windows 最高级别权限 编辑:程序博客网 时间:2024/05/01 11:02
#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;
}

I can't get what i want.the result is " a is 0".why is that??

==================================================

I think you're actually lucky that you get a is 0 instead of a crash. The problem is that getfunc takes the function pointer by value, so the myfunc = &add inside getfunc has no effect on the caller at all. Try

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

and in main:

getfunc(&myfunc);