Lesson/Example please

Fred Wright fw at fwright.net
Tue Mar 16 01:24:51 UTC 2021


On Sun, 14 Mar 2021, Hal Murray via devel wrote:

> [Context is cleaning up ntp_control]
>
> This will probably be simple after somebody gives me a good example and/or
> explains things to me.
>
> I want to put a (pointer to a) function in a field of a struct.
> The type of that function includes a pointer to the struct.
> I need to make several functions of that type.
>
> I assume I want a typedef for the type of the function.
>
> Can anybody give me a pointer to code that does this?  Or steer me in the
> right direction, or ...
>
> There is a recursive tangle of struct needs function and function needs 
> struct, but the function only needs a pointer to the struct so I think 
> that should work.

Typedefs are never mandatory, but they greatly improve readability where 
function types are involved.

The main piece you may be missing here is the incomplete structure 
definition.  This creates a structure type without specifying its content, 
which can be used in any context that doesn't require knowing the size of 
the structure or accessing any of its fields.  In particular, one can 
always declare a pointer to an incomplete structure type.

This happens automatically during a normal structure definition, which is 
why something like this is legal:

 	struct foo {
 		struct foo *next;
 	};

Here "struct foo" is an incomplete definition at the open brace, and a 
complete defition at the closing brace.

Incomplete definitions are most commonly used when structures need to 
refer to each other both ways, as in:

 	struct bar;

 	struct foo {
 		struct bar *bar;
 	};

 	struct bar {
 		struct foo *foo;
 	};

In your case, you probably want something along the lines of:

 	struct foo;

 	typedef int foo_func(struct foo *arg);

 	struct foo {
 		foo_func *func;
 	};

Fred Wright


More information about the devel mailing list