Can anyone please explain why a self reference on a structure is allowed, but not a variable of that type?

This is what i mean:

struct node{
  int a;
  struct node *n1;

/* This is allowed */
struct node {
  int a;
  struct node n1;

/* But not this */

What is the reason behind this? Can anyone please explin?

Well how do you define the structure in the second example? Maybe that's a little vague...How do you define the memory layout in the second example?

In the first example you have sizeof(int) plus sizeof(struct node *n1) plus padding.

In the second example what is the sizeof(struct node)? Its impossible to tell.


Hmm, i did not think about that. So, basically, its not possible to know the size of the struct in the second case, unlike the first case, wherein its a pointer and its size can be determined.

Am i right about that?


Just explaining what gerard4143 said in simple words.

First usage is allowed as what ever usage of pointer you make its still remains a pointer and takes up a standard amount of memory which is normally equal to the size of your integer variable.So it can be defined without any confusions.

In the second usage you are including a variable of the same structure type inside the structure. Now here in order to declare a variable of some data type you need to know how that data type is defined and the data type cannot be unambigiously defined until the compiler knows what all the variables within that structure.So one waits for other and no one gets completed.

But this is allowed

struct A
     int a;
     char b;
struct B
     int c;
     struct A varA;

As the definition of A knows how char and int are defined and their memory needs and before structure B is defined the compiler knows how structure A is defined.


Thanks for the explanation.