Bob Bob - 1 year ago 46
C Question

Struct function pointer error

In the struct my_struct, there is a function pointer called compute(). It is declared as such:

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

In a separate file, I initialize that struct so I can point that function to another one.

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

The problem is, no matter what I set the function pointer to, I get the following error for data.compute:

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

I've used data members of structs plenty of times using the '.' operator, but I've never used function pointers. Is there something different needed here?

Answer Source

It should work notationally, though since you've defined the structure as const, you can only initialize it and not assign to it after initialization.

However, that's a different error from the one you're getting. It's behaving a bit as if data isn't a simple word — as if it is macro expanded into something odd, or something along those lines. The structure type is declared in a header, isn't it? And it does have a semicolon after the }, doesn't it?

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?

At one level, there's not enough code — you've not provided an MCVE (Minimal, Complete, and Verifiable Example) — we have no code that we can compile and see the error you're seeing (or something similar). We'd need your header and a minimal set of code that shows the problem.

You are writing the data.compute = … inside a function, aren't you? (Hmmm: I suspect not — you must either use initialization … data = { … }; or move the assignment inside a function.)

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?

The first is static const struct my_struct but I was feeling too lazy to copy'n'paste. So, you need:

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

or something similar (assuming you include the <math.h> to provide a declaration for sin — or use some other function that you've already declared or defined). If you are stuck without a C99 or later compiler):

static const struct my_struct data = { sin };

You can't write assignments outside of functions — that is your problem. You must use an initializer, or write the assignment inside a function and remove the const.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download