Julien
Julien

Reputation: 91

Position of struct in C

To make my code as clear as possible, I am trying to do something like :

struct Test {
   int a; 
   int b;
   struct Test2 c;
};

struct Test2{
   int d;
};

Of course this code is wrong because struct Test2 is used before being defined. I want to declare the struct forward. So I typed struct Test2; before struct Test but it didn't work. Is there a solution?

I know it is possible with functions, so maybe it should be the case for structures?

Upvotes: 1

Views: 1024

Answers (2)

Anton F.
Anton F.

Reputation: 486

It only works if struct Test holds a pointer of type struct Test2*. If it holds an instance, struct Test2 must be defined before struct Test because the size of struct Test2 must be known.

Upvotes: 4

Mad Physicist
Mad Physicist

Reputation: 114230

The reason that this is not possible is that when you place a concrete struct Test2 object inside struct Test, you need to know the size of Test2 to determine the size of Test. But you can't know the size without knowing the full definition first.

Forward declarations allow you to use a pointer to a type, since you can point to something without knowing the details until later. While it may not completely satisfy your needs, you could do something like the following with a forward declaration:

struct Test {
    int a;
    int b;
    struct Test2 *c;
};

The reason that a function declaration works is that it tells you everything you need to know about how to interface with the function. You don't need the function itself for that.

Upvotes: 4

Related Questions