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! Node being a struct, n is allocated on the stack. You call getNode twice 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') once getNode returns, because the stack location that belonged to n may be overwritten by a different call. In short: don't do it. If you want CLR to allocate memory, make Node a class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With