関数ポインタ

#include <stdio.h>

void call(void (*f)(const char *), const char *); 
void print(const char *); 
void greeting(const char *); 

int main()
{
    call(print, "sotarok");
    call(greeting, "sotarok");
    return 0;
}

void call(void (*f)(), const char *msg)
{
    f(msg);
}

void print(const char *msg)
{
    printf("%s\n", msg);
}

void greeting(const char *msg)
{
    printf("Hello %s!\n", msg);
}

みたいなかんじ。


なんかうまく使う方法が思い浮かばない。

// funcptr_add.c
#include <stdio.h>
#include <string.h>

void add(void (*)(), void *, const void *, const void *); 
void int_add(int *, const int *, const int *); 
void str_add(char *, const char *, const char *); 

int main()
{
    char hoge[] = "hoge, ", fuga[] = "fuga", piyo[1024];
    int a = 1, b = 2, c;
    float f1 = 1.0, f2 = 3.0;

    //int_add(a, b, &c);
    add(int_add, &c, &a, &b);
    add(str_add, piyo, hoge, fuga);
    printf("%d\n", c); 
    printf("%s\n", piyo);

    return 0;
}

void add(void (*f)(), void *c, const void *a, const void *b) 
{
    f(c, a, b); 
}

void int_add(int *result, const int *a, const int *b) 
{
    *result = *a + *b; 
}

void str_add(char *result, const char *a, const char *b) 
{
    strcat(result, a); 
    strcat(result, b); 
}

あ、こりゃバッファオーバーフローしますけどね。