Static Linked List in C

We have discussed about the linked list data structure which is dynamic in nature (the memory is allocated during the run time). Now the question that might be on a few peoples minds is – can a linked link be implemented statically as well? This post tries to answer this question.


 


 

The fundamental purpose of a pointer-based linked list is to provide dynamic expansion but in cases where your linked list does not need to have dynamic size, you can use static storage for it. The automatic storage has the property that its lifetime ends when execution of the block where it’s declared terminates, so it’s difficult to use it for long-lived data. Also, there’s typically a bound on the amount of such storage you can obtain and past that Memory overflow will happen. And there is no way to detect when you’ve exceeded that bound.

Below code uses automatic storage to allocate nodes of linked list.

 
C implementation –
 

Download   Run Code

Output:

1 -> 2 -> 3 -> 4 -> 5 -> null

 


 

Above method would become a pain if number of nodes required is very large in the linked list. We can construct a linked list easily using iteration if the keys are given in the form of an array or any other data structure (using its iterator). Below is the implementation of the idea.

 
C implementation –
 

Download   Run Code

Output:

1 -> 2 -> 3 -> 4 -> 5 -> null

 


 

The lifetime of these nodes are the scope they are declared in, they no longer exists when the scope ends. We can verify that by placing our code inside block scope and try to access the nodes outside block scope.

 
C implementation –
 

Download   Run Code

Output:

Runtime Error

 


 

As discussed, Linked List nodes declared in automatic storage won’t hang around after you’ve left the scope they were defined in. The solution is to make it global.

 
C implementation –
 

Download   Run Code

Output:

1 -> 2 -> 3 -> 4 -> 5 -> null

 

 
Thanks for reading.




Please use ideone or C Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂