1,181 views
1 votes
1 votes
I have learnt that self-referential structure is one which contains a structure of same type in it as an element. 
But I have a doubt regarding how that line is compiled successfully (i.e, how compiler knows how much space should 
be allocated and its elements)when the definition of that structure is not yet finished?  

struct node {
      int data;
      struct node *next;
};

correct me If I am wrong in understanding this.

2 Answers

1 votes
1 votes

Memory allocation is not always done at compilation.

  • Global and static variables are allocated fixed size in the data section at the time of compilation and hence mostly there sizes need to be declared at the time of compilation itself.
  • Local variables to a function are not allocated space at the time of compilation. It is done at execution on the program stack section.
  • The self referential structures which you are talking about is mostly created dynamically using malloc function, in this case the space is allocated in the heap section at runtime dynamically.
  • Considering your code:
struct node {
      int data;                // memory is allocated to this
      struct node *next;      // memory is allocated only to this pointer not to the node pointed by it 
};
  • The compiler only provides space enough to store ' int data' and  a pointer 'next'. The location for next itself is not located. It has to be created again using a different malloc call and should be assigned to this previous node's next pointer.

 

0 votes
0 votes
I think in view of memory allocation, while allocation only the data type is important. So the variable 'next' in your example is nothing but a pointer and in most architectures all pointers are of same size (it may vary on some architecture).

But you can always know the space needed to be allocated from the data type, which is here of type pointer to structure. You need not know anything about the data items within structure.

Related questions

7 votes
7 votes
3 answers
1
Parshu gate asked Nov 20, 2017
741 views
What is the output of the following program?#include<stdio.h int main() { int array[]={10, 20, 30, 40}; printf(“%d”, -2[array]); return 0; }$-60$$-30$$60$Garbage valu...
2 votes
2 votes
2 answers
2
piya asked Jun 13, 2018
830 views
#include <stdio.h int main(void) { int a=5, b=10; printf("%d%d",a,b); make_it(b,a,a+b); printf("%d%d",a,b); return 0; } int make_it(int x,int y, int z){ x*=y+z; y=x<<1; z...
1 votes
1 votes
1 answer
4
Na462 asked Jan 8, 2019
1,399 views
#include <stdio.h>main (){unsigned x = -10;int X = 20;if (X x) printf ("Hello");else{ printf ("%d",x); printf ("Jello"); }}