void *函数指针

时间:2013-11-03 08:11:44

标签: c function pointers

我为函数指针创建了一个typedef,它接受一个整数并返回一个void *:

typedef void* (*fp)(int index);
然后我创建了一个包含fp和另一个相同类型结构的结构:

typedef struct fp_holder {
    fp function_pointer;
    iterable *next;
} fp_holder;

我试图找出如何在fp_holder中调用fp。

为了测试这一点,我做了以下事情:

void *test_fp(int index) {
    if (index == 0) {
        printf('H');
        fflush(stdout);
        return [something_that_works];
    }
    else if (index == 1) {
        printf('e');
        fflush(stdout);
        return [something_that_works];
    }
    else if (index == 2) {
        printf('l');
        fflush(stdout);
        return [something_that_works];
    }
    else if (index == 3) {
        printf('l');
        fflush(stdout);
        return [something_that_works];
    }
    else if (index == 4) {
        printf('o');
        fflush(stdout);
        return [something_that_works];
    }
    else {
        return (void *) NULL;
    }
}

fp_holder *a = (fp_holder *) malloc(sizeof(fp_holder));
a->function_pointer = test_fp;
a->next = NULL;

因此,通过所有设置,我尝试通过尝试以下方法调用函数_pointer:

a->function_pointer(0);
(*a->function_pointer)(0);
((*)a->function_pointer)(0);

我无法弄清楚为什么那些不起作用。 帮助将不胜感激! :)

修改

我想做什么: 用参数调用一个function_pointer。

我现在会尝试一些答案,看看会发生什么。

EDIT2

回答!我通过执行a-> function_pointer(0)来调用它,但是什么给了我一个分段错误[这就是我的问题 - 也许我应该澄清一下]是printf语句而不是我的调用。 printf需要一个字符串而不是我输入的字符串。

2 个答案:

答案 0 :(得分:5)

您的原始代码是否确实

printf('H');

而不是

printf("H");

您发布的代码的简化版本,其中包含printf的正确参数:

#include <stdio.h>

typedef void* (*function_pointer_t)(int index);

struct function_holder {
    function_pointer_t callback;
};

void* testFn(int i)
{
    printf("testFn %d\n", i);
}

int main(void) {
    struct function_holder fh = { testFn };
    struct function_holder* fhp = &fh;

    fh.callback = testFn;
    fh.callback(1);
    fhp->callback(2);

    return 0;
}

按预期工作:http://ideone.com/1syLlG

答案 1 :(得分:0)

您的代码有几个错误。我不确定您要通过此代码实现什么,但这是您的工作代码。

#include "stdio.h"
#include "string.h"
#include "stdlib.h"

typedef void* (*fp)(int index);
typedef struct fp_holder {
    fp function_pointer;
    struct fp_holder *next;
} fp_holder;

void *test_fp(int index) {
    if (index == 0) {
        printf("H");
        fflush(stdout);
        return "H";
    }
    else if (index == 1) {
        printf("e");
        fflush(stdout);
        return "e";
    }
    else if (index == 2) {
        printf("l");
        fflush(stdout);
        return "l";
    }
    else if (index == 3) {
        printf("l");
        fflush(stdout);
        return "l";
    }
    else if (index == 4) {
        printf("o");
        fflush(stdout);
        return "o";
    }
    else {
        return (void *) NULL;                                                                                                                                    }
    }


int main() {
    fp_holder *a = (fp_holder *) malloc(sizeof(fp_holder));
    a->function_pointer = test_fp;
    a->next = NULL;
    a->function_pointer(0);
}
相关问题