结构函数指针错误

Struct function pointer error

在结构体my_struct中,有一个叫做compute()的函数指针。它是这样声明的:

struct my_struct
{
  double (*compute) (double input);
}

在一个单独的文件中,我初始化了那个结构,这样我就可以将该函数指向另一个。

static const struct my_struct data;
data.compute = ......

问题是,无论我将函数指针设置为什么,data.compute 都会出现以下错误:

error: expected '=', ',', ';', 'asm', or '__attribute__' before '.' token

我已经使用“.”多次使用结构的数据成员。运算符,但我从未使用过函数指针。这里需要一些不同的东西吗?

它应该在符号上工作,但由于您已将结构定义为 const,因此您只能对其进行初始化,而不能在初始化后对其进行赋值。

但是,这与您收到的错误不同。它的表现有点好像 data 不是一个简单的词——就好像它是宏扩展成一些奇怪的东西,或者类似的东西。结构类型是在header中声明的,不是吗?它在 } 后面确实有一个分号,不是吗?

Yeah, const isn't the problem. I've tried removing it, only to get the same error. Any idea how to solve that last part you're talking about?

一方面,没有足够的代码——您没有提供 MCVE (Minimal, Complete, and Verifiable Example)——我们没有代码可以编译并查看您看到的错误(或类似的东西) .我们需要您的 header 和显示问题的最少代码集。

您是在函数内部编写 data.compute = … ,对吗? (嗯:我怀疑不是 — 您必须使用初始化 … data = { … }; 或将赋值移动到函数中。)

No, it's not in a function. Could you elaborate a little more on … data = { … };? I don't recognize that syntax; what does the first represent?

第一个 static const struct my_struct 但我懒得复制粘贴了。所以,你需要:

static const struct my_struct data = { .compute = sin };

或类似的东西(假设您包含 <math.h> 来为 sin 提供声明——或者使用您已经声明或定义的其他函数)。如果您在没有 C99 或更高版本的编译器的情况下陷入困境):

static const struct my_struct data = { sin };

你不能在函数之外写赋值——那是你的问题。您必须使用初始值设定项,或在函数内编写赋值并删除 const.