简体   繁体   中英

incompatible pointer types assigning to 'void (*)(void *)' from 'int (int *)'

I have written code in C below, but get a warning on p = getNext;

incompatible pointer types assigning to 'void (*)(void *)' from 'int (int *)'

int getNext(int *p){
    return rand();
}
void testFunc(void (* p)(void *)){
    printf("right!\n");
}
int main(int argc, char const *argv[])
{
    void (*p)(void *);
    p = getNext;
    testFunc(p);
    return 0;
}

I tried to solve it by

p = (void *)getNext;

It works. But I have no idea why it works. Does (void *) cast the getNext to a new function that can return undefined type of data? Can someone explains it?

getNext is a function of type int getNext(int *p) , and it decays to a pointer of to a function of type int (*)(int *) . this is incompatible with your other pointer type, and you would need a cast. Hence:

void (*p)(void *);
p = (void (*)(void*))getNext;

The problem is that when you call the function through the pointer you must cast it back to the original type... Perhaps you meant to use int (*p)(int *); everywhere.


A typedef simplifies handling function pointers. For example:

typedef int (*CALLBACK)(int *);

void testFunc(CALLBACK p){
    printf("right!\n");
}

...
    CALLBACK p = getNext;
    testFunc(p);

The converting to void * and then to a function is doubly invalid when it comes to standard C, but it is allowed as an extension in POSIX, which has the dlsym function that returns a void * that could point to a function or an object alike.

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