开发者

function pointer of typedef

开发者 https://www.devze.com 2023-02-20 06:51 出处:网络
#include <st开发者_开发问答dio.h> typedef int (*func)(int); int add (int a) { return ++a; } int getfunc(func myfunc)
#include <st开发者_开发问答dio.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);


No question here, but you need to pass by address, not by value. the problem seems to be getfunc(myfunc);

Fix getFunc to:

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

and call it with getFunc(&myfunc);


It should be more like this (changes flagged with <<<):

#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;
}


myfunc is a pointer. You created it but never assigned it a value. Then you call getfunc with a wild pointer!

Try this (your version, simplified):

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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号