Singo
Singo

Reputation: 93

Compile error. Definition mismatch. void (*)(void *)

I have a function that takes following argument:

int setvalue(void (*)(void *));

In order to satisfy parameter: void (*)(void *), I created a function like this:

    static void *freeFunction(void *freeAbc)
    {
        AllocAbc *abc = (AllocAbc*) freeAbc; 
        if (abc)
        {
            delete abc;
        }
        return NULL;
    }

And I'm trying to use both together as :

    AllocAbc *allocAbc = new AllocAbc();
    ...
    void *freeAbc = (void *) allocAbc;
    if (setvalue (freeFunction(freeAbc)) < 0)
    {           
        ...
    }

I get an error saying error: invalid conversion from ‘void*’ to ‘void (*)(void*)’ [-fpermissive]

What should be changed here (either in freeFunction definition or the way I use both) to make it work.

Thanks.

Upvotes: 1

Views: 89

Answers (3)

Emil Laine
Emil Laine

Reputation: 42828

freeFunction returns void*, but setvalue wants a function that returns void. They are clearly not the same type.

Also you're passing the return value of freeFunction to setvalue, but setvalue expects a function pointer.

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361605

Your function should return void not void *.

static void freeFunction(void *freeAbc)
{
    ...
}

The (*) indicates that setvalue's parameter is a function pointer. It's not part of that function's return type.

(void (*)(void *)
 ^^^^  ^  ^^^^^^
  ||   |    ||
  ||   |    ++ parameter types
  ||   |
  ||   + function pointer
  ||
  ++ return type 

Also, to call setvalue you need to pass the function name without calling it.

if (setvalue(freeFunction) < 0)

To make it clearer, you may want to add an & to indicate that you're not calling the function. & is optional when passing function pointers, so this is just a readability thing.

if (setvalue(&freeFunction) < 0)

Upvotes: 3

Benjy Kessler
Benjy Kessler

Reputation: 7616

You have two problems:

  1. Your freeFunction returns void instead of void *.
  2. You are passing the return value of freeFunction(freeAbc) into setValue instead of a pointer to the function itself.

Upvotes: 3

Related Questions