Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct containing a function pointer with itself as a return type in C

Got the following data struct:

typedef struct
{
    lamp *lamp;
    unsigned char a;
    unsigned char b;
    unsigned char c;
    unsigned char d;
    unsigned char e;
    void (*func)(struct event *);
} event;

The last line inside the struct is supposed to be a pointer to a function with return type void with pointer to an event as an argument such as:

void function(event *evt);

Though, I get the following warning message: "its scope is only this definition or declaration, which is probably not what you want". Is this right or wrong?

like image 961
user2182011 Avatar asked Mar 18 '13 11:03

user2182011


People also ask

Can a structure struct contain a pointer to itself?

A structure containing a pointer to itself is not a problem. A pointer has a fixed size, so it doesn't matter how big the size of the structure it points to is. On most systems you're likely to come across, a pointer will be either 4 bytes or 8 bytes in size.

Which structure contains a pointer to its own type?

Pointers to structures Although a structure cannot contain an instance of its own type, it can can contain a pointer to another structure of its own type, or even to itself. This is because a pointer to a structure is not itself a structure, but merely a variable that holds the address of a structure.

Can a struct have itself?

A structure T cannot contain itself.


1 Answers

Your struct needs needs to be defined like this:

typedef struct event  // <<< note the `event` tag here
{
    lamp *lamp;
    unsigned char a;
    unsigned char b;
    unsigned char c;
    unsigned char d;
    unsigned char e;
    void (*func)(struct event *);
} event;              // <<< you can still keep `event` as a typedef
                      //     which is equivalent to `struct event`
like image 150
Paul R Avatar answered Nov 09 '22 23:11

Paul R