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

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

0

4 Answers 4

4

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.