Reputation: 1362
I am implementing Linked List in C# so I use Two Approaches
First Approach
unsafe public struct Node
{
public int info;
public Node* link;
}
Here Is Add Node Method
public void AddNode( int a)
{
Node temp = new Node();
temp.info = a;
if (Head == null)
{
Head = Current = &temp;
}
else
{
(*Current).link = &temp;
Current = &temp;
}
}
When I run This Code It does not save memory means It create an instance of Node temp = new Node();
Structure as long as it is inside AddNode Its memory is save but when I print It outside this method using Head its give me NullRefrenceException
Second Approach
By Using Class And Objects
public class Node
{
public int info;
public Node link;
}
class Linked_list
{
public Node Head;
public Node Current;
public void insert_element_linkedlist( int a)
{
Node temp = new Node();
temp.info = a;
if (Head == null)
{
Head = Current = temp;
}
else
{
Current.link = temp;
Current = temp;
}
}
}
The Second method is working perfectly means Every instance of temp node Node temp = new Node();
is save in memory .
Question : Why It does not save structure instance ?
Sorry For My Sub Standard English.
Upvotes: 0
Views: 1665
Reputation: 8551
The structure instance, being a value type, gets created on the stack, so when AddNode
returns it is cleaned up and you are left with pointers to a random place in memory. Simply creating a pointer to a variable is not enough to keep it alive.
Upvotes: 1