简体   繁体   中英

What is the difference between void* (*)() and void*?

In one of my programs, I'm getting the error

invalid conversion from 'void* (*)()' to 'void*' [-fpermissive]

I'm trying to understand the difference between these two data types. It is very confusing.

What I think that these data types are:
void* (*)() So this data type is a pointer to a void ( void* ) which also has another pointer ( (*) ), and for some odd reason, it has empty parentheses. So What I imagine the memory for this data type looks like is |--void address--|--pointer of unknown type--|--something denoting no arguments--|

then there's void* . This seems simple, and it only represents the address of a function. The memory model should be as simple as |--void address--|.

Why this is so weird, is that the function that is thrown the error is as follows.

void callFunction(void *voidThing){
void *testVariable = voidThing;
}

And as far as I am aware, this creates a testVariable of type pointer, and that pointer is to a void. This function also takes in a parameter of type pointer, and that pointer is also to a void.

Why is the compiler throwing an error, even though the local variable is of the same type of the parameter? What is the difference between the variables in terms of the memory footprint of the two?

These are types :

  • void * - pointer to void (this can point to any object, not to a function)
  • void * () - function taking no arguments and returning void *
  • void * (*) () - pointer to function taking no arguments and returning void *

Example of a declaration of an identifier for each of the above, respectively:

void *object_ptr;    // variable: pointer to object

void *function();    // function  (not a variable)

void * (*function_pointer)();  // variable: pointer to function

The syntax for function types places the identifier before the argument list , a similar thing happens with arrays. This is called infix notation .

Pointer declarators are postfix , ie the identifier comes after the * .

In void * (*) () the first set of parentheses are necessary because void * *() would be a different type (the declaration grammar results in void * * staying together).


The callFunction function is correct in itself, however the error message probably comes from trying to call this with incorrect argument, eg the address of a function. void * can only hold the address of an object .

Some platforms may allow reinterpret_cast to be used to cast an object pointer to a function pointer or vice versa, this feature is conditionally-supported with implementation-defined semantics , meaning that implementations may or may not allow it, but must document the behaviour if they do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM