Typecasting a function pointer
c, function-pointers, typecast-operator
Solution
There are functions and there are function pointers. `strcmp` is a function, linked to your project. When the identifier `strcmp` is used in an expression, you get a function pointer to that function. But you cannot change "where strcmp points to" because `strcmp` is a function and not a pointer.
C allows conversions between different function pointer types. However, should you try to call a function through a function pointer of incompatible type, you invoke undefined behavior.
int (*funcPtr)(void*,void*);
is not compatible with `strcmp`, which has the following format:
int strcmp(const char *s1, const char *s2);
Meaning:
funcPtr = (int(*)(void*, void*))strcmp; // this is ok but not very meaningful
funcPtr(); // this is NOT ok, invokes undefined behavior
In order to actually call the function `strcmp` through that function pointer, you would have to cast back to the correct type, which is `int (*)(const char*, const char*)`.
Problem
I know this is a duplicate. I've searched already but none address the problem I'm having. NOTE in an attempt to single out my confusion I have tried to simplify the typecast from the original. Hopefully it isn't undefined behaviour Declaring a pointer to a function ``` Int (*funcPtr)(void*,void*); ``` Strcmp declaration ``` int strcmp (char *, char *); ``` Typecasting a function pointer ``` FuncPtr = (int (*)(void*, void*))strcmp ``` This is where I get confused. I understand Typecasting a function pointer we have created. So type casting FuncPtr for example just changes what type of function funcPtr can point to. I have also read that the name of a function Is a function pointer to itself so Typecasting strcmp and using my understanding from above, ``` int (*)(void*, void*))strcmp ``` Strcmp can now point to a function that takes two pointers to void and returns an int which Is clearly wrong as like arrays I think the function name can't be a pointer to another function. Because of my understanding above I fail to see how you can assign the address of strcmp to FuncPtr with the following typecast ``` FuncPtr = (int (*)(void*, void*))strcmp ``` As changing what the function pointer strcmp points to doesn't change the arguments and return type of strcmp. I would really appreciate some knowledge I'm just so confused.