I created a structure pointer, but each call for the new node returns the same address. But i expected different address to be returned for each invocation of the new node. Can someone please help?
public unsafe struct Node
{
public int Data;
}
class TestPointer
{
public unsafe Node* getNode(int i)
{
Node n = new Node();
n.Data = i;
Node* ptr = &n;
return ptr;
}
public unsafe static void Main(String[] args)
{
TestPointer test = new TestPointer();
Node* ptr1 = test.getNode(1);
Node* ptr2 = test.getNode(2);
if (ptr1->Data == ptr2->Data)
{
throw new Exception("Why?");
}
}
}
Don’t be fooled by the
Node n = new Node();syntax!Nodebeing a struct,nis allocated on the stack. You callgetNodetwice from the same function in the same environment, so naturally you are getting two pointers to the same stack location. What’s more these pointers become invalid (‘dangling’) oncegetNodereturns, because the stack location that belonged tonmay be overwritten by a different call. In short: don’t do it. If you want CLR to allocate memory, makeNodea class.