Function Pointers

A function is the address of the entry point to a group of instructions bundled together into the function construct. A function pointer stores the entry-point address of a function. If we dereference a function pointer, it is the same as calling the function.

When declaring a function pointer we need to separate the pointer declaration from the type of the return value. To separate the two we wrap the pointer declaration in a set of parentheses.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

long addNums(int a, int b);
long subNums(int a, int b);
long multNums(int a, int b);

char *reverseStr(char *str);

int main()
{
    char *strOrig = "Greetings, Professor Falken";
    char *str = NULL;

    int i = 0;
    long answer = 0;
    int iVarOne = 42;
    int iVarTwo = 73;

    long (*mathFunction)(int a, int b);

    long (*mathArray[3])(int a, int b);

    char *(*stringFunction)(char *str);

    stringFunction = reverseStr;

    printf("Address of string reverse function is %p\n", reverseStr);
    str = (*stringFunction)(strOrig);

    printf("%s backwards is %s\n", strOrig, str);

    mathArray[0] = addNums;
    mathArray[1] = subNums;
    mathArray[2] = multNums;

    for(i = 0; i < 3; i++){
        answer = (*mathArray[i])(iVarOne, iVarTwo);
        printf("%ld\n", answer);
    }

    return 0;
}

long addNums(int a, int b){
    return a + b;
}

long subNums(int a, int b){
    return a - b;
}

long multNums(int a, int b){
    return a * b;
}

char *reverseStr(char *str){
    int i, j, strLength;

    char *returnString = NULL;

    if(str != NULL){
        strLength = strlen(str);
        returnString = (char *)malloc(sizeof(char) * (strLength  + 1));
        if(returnString != NULL){
            for(i = 0, j = strLength - 1; i < strLength; i++, j--){
                returnString[i] = str[j];
            }
            returnString[strLength] = '\0';
        }
    }
    return returnString;
}

The function names act as address tags in the same way that array names act as address tags.

Leave a comment