我创建了一个结构指针,但每次调用新节点都会返回相同的地址。但是我希望每次调用新节点都会返回不同的地址。有人可以帮忙吗?
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?");
}
}
}
最佳答案
不要被 Node n = new Node();
语法所迷惑! Node
是一个结构,n
分配在堆栈上。您从同一环境中的同一函数两次调用 getNode
,因此您自然会获得指向同一堆栈位置的两个指针。更重要的是,一旦 getNode
返回,这些指针就会变得无效(“悬挂”),因为属于 n
的堆栈位置可能会被不同的调用覆盖。简而言之:不要这样做。如果您希望 CLR 分配内存,请将 Node
设为一个类。
关于c# - 在 C# struct pointer 中返回相同的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4275082/