结构声明和函数指针之间的循环依赖

标签 c

<分区>

我有一个结构,它有一个函数指针作为成员变量。函数指针将指向结构的指针作为其参数之一。

通过查看此处针对此类循环依赖项发布的解决方案,我使用了前向声明以便能够编译。

我仍然有无法初始化结构的问题。下面发布的是代码和输出。

编辑:我之前的 MVCE 没有正确重现问题。我可以通过命名结构而不是仅仅使用结构别名来编译它。虽然不确定为什么。

#include "stdio.h"

//Forward declaration
struct data;

typedef int(*funcPtr) (struct data* a);

typedef struct
{
    int a;
    int b;
    funcPtr foo;
}data;

int foo(data* pData)
{
    return 0;
}

static data testData[] = {{1,1,foo}, {0,2,foo},};

int main()
{
    printf("Just trying to compile this program\n");
    return 0;
}

错误输出--

compileError.c:20:1: warning: initialization from incompatible pointer type [enabled by default]
static data testData[] = {{1,1,foo}, {0,2,foo},};
^
compileError.c:20:1: warning: (near initialization for \u2018testData[0].foo\u2019) [enabled by default]
compileError.c:20:1: warning: initialization from incompatible pointer type [enabled by default]
compileError.c:20:1: warning: (near initialization for \u2018testData[1].foo\u2019) [enabled by default

最佳答案

函数 foofuncPtr 不兼容 - 它返回一个 int,而不是一个 void

此外,您的变量被声明为数组,但您使用单个值对其进行初始化 - 删除 []

关于结构声明和函数指针之间的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36492411/

相关文章:

c++ - 如何使用c在net snmp中发送v2陷阱

c - 如何从文件中读取数字并计算平均值?

c - 如何将函数符号映射到地址范围

c - 程序无法加载共享库GCC

c - 二叉搜索树插入程序显示段错误

c - 指针指向 Void 的内存分配

c++ - 预期的声明说明符或 '...' 之前的 'MLD_PACKET'

c - 从另一个#define 访问#define 中声明的变量

c - 为什么这个练习代码在长度 == 0 时会失败?

c - Doxygen 构造多种语言