Question

Is there a way to correctly define structs in a circular fashion (in C)? In other words:

//struct struct1;  Is this ok??

struct struct2 {

    struct struct1* someStruct1Var;
    //Other variables
};

struct struct1 {
   //Some variables
   struct2* (*someFunc)(struct2* someStruct2Var);
}

The behavior I basically want is that the first struct has a variable that is a pointer to an instance of the second (which is a global variable and only 1 will exist). Then I want the second struct to have function pointers that return the type of the first struct. I want this behavior in order to implement basic object-oriented-like classes/objects. If there is a similar method that can accomplish the same thing, that would also be very helpful. Again, what I need is to have a class struct (struct1) containing function pointers that take as arguments and return variables the type of the object (struct2). Then, I need each object to have a reference to its global class variable (which is of type struct1).

Thank you!

Was it helpful?

Solution

You should forward declare your struct

typedef struct struct1 struct1;
typedef struct struct2 struct2;

struct struct2 {

    struct1* someStruct1Var;
    //Other variables
};

struct struct1 {
   //Some variables
   struct2* (*someFunc)(struct2* someStruct2Var);
}

Doing it with a typedef help to omit the struct keyword to name the type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top