Expand|Select|Wrap|Line Numbers
- #include <stdlib.h>
- #include <stdio.h>
- // The structure containing the function pointer
- typedef struct {
- int (*MyFunctionPointer)(int);
- } MyStructure;
- // A function to take a function pointer, initialize it with a MyStructure, and return it
- MyStructure *put_function_pointer_into_structure(int (*FunctionPointer)(int))
- {
- MyStructure *StructureInstance = {FunctionPointer};
- return StructureInstance;
- }
- // A trivial function for testing purposes
- int divide_by_two(int number)
- {
- return number/2;
- }
- // Entry-point. Performs the testing
- int main(int argc, char *argv[])
- {
- MyStructure *StructureWithFunctionPointer = put_function_pointer_into_structure(divide_by_two);
- printf("The number is %i, half of it is %i\n", 9000,
- StructureWithFunctionPointer->MyFunctionPointer(9000));
- return EXIT_SUCCESS;
- }
func_ptr_test.c:12: warning: initialization from incompatible pointer type
(This refers to the line MyStructure *StructureInstance = {FunctionPointer};)
Of course that is just a warning and I can run the program regardless, but it gives a segfault immediately (or a "general protection error" for you Windows people out there).
I can't for the life of me figure out what is wrong with my code, any suggestions will be highly appreciated.
I'm using GCC (version 4.1.3).