爱悠闲 > 函数指针的传递问题

函数指针的传递问题

分类: linux-C  |  标签: include,function  |  作者: taolinke 相关  |  发布日期 : 2014-12-01  |  热度 : 100°
#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
);