在结构体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
.
关于c - 结构体函数指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40392961/