gpt4 book ai didi

c - 函数指针 typedef 的前向声明

转载 作者:太空狗 更新时间:2023-10-29 17:19:17 24 4
gpt4 key购买 nike

我遇到了一个特殊的问题。最好只向您展示我正在尝试做的事情,然后再进行解释。

typedef void functionPointerType ( struct_A * sA );

typedef struct
{
functionPointerType ** functionPointerTable;
}struct_A;

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

有人知道这是怎么实现的吗?

编辑:代码中的小修正

最佳答案

按照您的建议转发声明:

/* 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];
};

例如:

#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;
}

输出:

stdout: 4stderr: 4

See online demo http://ideone.com/PX880w .


As others have already mentioned it is possible to add:

typedef struct A struct_A;

如果最好省略 struct 关键字,则在函数指针 typedefstruct A 的完整定义之前。

关于c - 函数指针 typedef 的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15625677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com