Memory allocation to variable in a method

59 views Asked by At

I have a question on how a particular line of code works in regards to memory allocation. I am referring a piece of code to convert array list into linkedlist.

Attaching the code below

// C# implementation of the above approach 
using System; 
          
class GFG
{ 
    // Representation of a node
    public class Node 
    {
        public int data;
        public Node next;
    }
      
    // Function to insert node
    static Node insert(Node root, int item)
    {
        Node temp = new Node();
        Node ptr;
        temp.data = item;
        temp.next = null;
        if (root == null)
        {
            root = temp;
        }
        else
        {
            ptr = root;
            while (ptr.next != null)
            {
                ptr = ptr.next;
            }
    ======> ptr.next = temp;
        }
        return root;
    }
      
    static void display(Node root)
    {
        while (root != null) 
        {
            Console.Write(root.data + " ");
            root = root.next;
        }
    }
      
    static Node arrayToList(int []arr, int n)
    {
        Node root = null;
        for (int i = 0; i < n; i++)
            root = insert(root, arr[i]);
        return root;
    }
      
    // Driver code
    public static void Main(String []args)
    {
        int []arr = { 1, 2, 3, 4, 5 };
        int n = arr.Length;
        Node root = arrayToList(arr, n);
        display(root);
    }
}

So my doubt is once we assign an object Ptr to root then whatever change we make to Ptr will be reflected in root since both point to same memory. In 3rd iteration Ptr =Ptr.next, so it is referring to new memory location and when you inspect element Ptr it is assigned 2nd child node. So how come root object gets modified by ptr=ptr.next with different memory address. That is my question.

Thanks

0

There are 0 answers