c# - 在 C# struct pointer 中返回相同的地址

标签 c# pointers struct

我创建了一个结构指针,但每次调用新节点都会返回相同的地址。但是我希望每次调用新节点都会返回不同的地址。有人可以帮忙吗?

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/

相关文章:

c - 访问全局整数数组时出现段错误

C:声明一个指针然后将其用作数组,内存分配

swift - 比较符合协议(protocol)的结构

c++ - 解析字符串并将整数值插入结构 vector C++

无法弄清楚我是如何遇到段错误的

c# - Python 的 os.path 库等同于 C#

c# - 无法将 'int'隐式转换为 'System.Reflection.BindingFlags'

c# - 使用 MS SDK 使用 Kinect 跟踪张开或闭合的手?

c - 从指向数组的指针使用 memcpy

c# - 如何从 FluentValidation 获取验证规则