Using function pointers (Function pointer Part II)

Learn how to use function pointers. For example passing them to other functions and so on.

#include <stdio.h>

/**
 * Using a function pointer in a structure.
 */
struct _Object {
    void (* functionPointer)();
    int value;
};

/**
 * Passing a function pointer to a function.
 */
void passFunction(void (* functionPointer)()) {
	/* call our passed function */
	functionPointer();
}

void testFunction() {
	puts("hello");
}

void testFunction2() {
	puts("juhu");
}

int main(int argc, char * argv[]) {
    /* pointer to void function with no parameters myFunction */
    void (* myFunctionPointer)() = testFunction;
    /* call original function */
    testFunction();
    /* call our new pointer function */
    myFunctionPointer();

    /* create struct */
    struct _Object Object;
    Object.value = 1;
    Object.functionPointer = testFunction;

    printf("%d\n", Object.value);
    Object.functionPointer();

    /* Add function pointer to our gobal array. */
    int functionPointers[2];

    functionPointers[0] = (int)testFunction;
    printf("%d\n", functionPointers[0]);

    functionPointers[1] = (int)testFunction2;
    printf("%d\n", functionPointers[1]);

    /* Creepy! but possible. */
    ((void (*)()) functionPointers[0])();
    ((void (*)()) functionPointers[1])();

    return 1;
}
  • Digg
  • del.icio.us
  • Facebook
  • Technorati
  • Twitthis
  • FriendFeed

POST A COMMENT

  • You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>