Initializing a building pointer in C #

unsafe public class Temp
{
    public struct Node
    {
        Node *left;
        Node *right;
        int value;
    }

    public Temp()
    {
        Node* T=new Node();
        T->left=null;
        T->right=null;
        T->value=10;
    }
}

main()
{
    Temp temp=new Temp();
}

It gives an error that the object reference is not set to the object instance. How can I do this when I want to make an AVL Tree program (which I created and tested in C ++, but copying in C # gives an error)

+5
source share
3 answers

Do not try to use pointers to C # like this. If you port C ++ code that uses pointers as references, use reference types instead. Your code will not work at all; "new" does not allocate structures from the heap, firstly, and even if pointers are required in the C # pointer; C # is the language that garbage collects.

unsafe, , #. , , , .

:

public class Temp // safe, not unsafe
{
    public class Node // class, not struct
    {
        public Node Left { get; set; } // properties, not fields
        public Node Right { get; set; } 
        public int Value { get; set; }
    }

    public Temp()
    {
        Node node = new Node();
        node.Left = null; // member access dots, not pointer-access arrows
        node.Right = null;
        node.Value = 10;
    }
}
+17

:

Node* T=new Node();

#, new Node() Node ( ), Node* ( ). stackalloc.

, , ++ #!!

+4

.NET , . new ed Node, , , , " ". Node* T = new Node() , .

What you are trying to do is wrong: don't copy and paste C ++ code in C #, this is stupid. If you've already tested, C ++ components use the .NET / unmanaged interop to marshal data between the two worlds, although I would not recommend doing this at this level of abstraction. If you are doing the exercise, implement the AVL tree only in the .NET world, otherwise use one of the frame collections with equivalent functionality, for example. SortedSetor SortedDictionary...

+2
source

All Articles