It is not allowed to declare a variable of same structure type but it is allowed to declare a pointer. For example, Code: struct node { int a; struct node x; //not allowed struct node *pnext; //allowed }; My question is when we can declare a pointer of same type why not a variable of same type. I will be exremely grateful if somebody answers my question. Thanks Iqbal
It is not allowed to declare a variable of same structure type but it is allowed to declare a pointer. For example, Code: struct node { int a; struct node x; //not allowed struct node *pnext; //allowed }; My question is when we can declare a pointer of same type why not a variable of same type. I will be exremely grateful if somebody answers my question. Thanks Iqbal
Re: C--Structures(inside structure declaration of variable of same type is not allowe There is a very very good reason for this. If the variable isn't defined yet, can't you declare it first and then define it? (one might ask) Code: struct node { int a; struct node x; //not allowed }; This is how I see it. Follow in your mind what the compiler would do when you declare a variable of type struct node 1) It sees it has to allocate space for an integer. 2) It sees it has to allocate space for a struct node 3) It looks at the definition of struct node and then... 4) Repeats steps 1 - 3 indefinitely If this were not a compiler error, then the compiler would run until the computer crashed. But! You can declare a pointer to the type inside the struct. Follow what happens in that case 1) It sees it has to allocate space for an integer. 2) It sees it has to allocate space for a pointer (Constant between all types - typically 4 bytes) 3) Sets the type of the pointer to point to a struct node (so that it knows how to increment the pointer if necessary) 4) Variable definition succeeds! Perhaps it is well to know *why* things are the way they are.