函数指针typedef的前向声明

mar*_*o87 7 c typedef function-pointers forward-declaration

我遇到了一个特殊的问题.最好只是向您展示我正在尝试做什么,然后解释它.

typedef void functionPointerType ( struct_A * sA );

typedef struct
{
    functionPointerType ** functionPointerTable;
}struct_A;
Run Code Online (Sandbox Code Playgroud)

基本上,我有一个结构struct_A,指向一个函数指针表,其参数类型struct_A.但我不确定如何进行编译,因为我不确定如何或是否可以转发声明这一点.

谁知道如何实现这一目标?

编辑:代码中的小修复

hmj*_*mjd 10

按照你的建议转发声明:

/* Forward declare struct A. */
struct A;

/* Typedef for function pointer. */
typedef void (*func_t)(struct A*);

/* Fully define struct A. */
struct A
{
    func_t functionPointerTable[10];
};
Run Code Online (Sandbox Code Playgroud)

例如:

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

struct A;

typedef void (*func_t)(struct A*);

struct A
{
    func_t functionPointerTable[10];
    int value;
};

void print_stdout(struct A* a)
{
    printf("stdout: %d\n", a->value);
}

void print_stderr(struct A* a)
{
    fprintf(stderr, "stderr: %d\n", a->value);
}

int main()
{
    struct A myA = { {print_stdout, print_stderr}, 4 };

    myA.functionPointerTable[0](&myA);
    myA.functionPointerTable[1](&myA);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

stdout: 4
stderr: 4

参见在线演示http://ideone.com/PX880w.


正如其他人已经提到的那样,可以添加:

typedef struct A struct_A;
Run Code Online (Sandbox Code Playgroud)

在函数指针typedef和完整定义之前,struct A如果最好省略struct关键字.