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 error that Object reference not set to instance of an object. How can I do it when I want to make AVL Tree Program(which I have created and tested in C++ but copying in C# gives error)
Initialization of Structure Pointer After a structure pointer is declared we need to initialize it to a variable before using it. To initialize a variable we need to provide address of the structure variable using the & operator.
The initializer is an = (equal sign) followed by the expression that represents the address that the pointer is to contain. The following example defines the variables time and speed as having type double and amount as having type pointer to a double .
Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.
Don't try to use pointers in C# like this. If you are porting C++ code that uses pointers as references, instead use reference types. Your code will not work at all; "new" does not allocate structs off the heap, for one thing, and even if it did pointers are required to be pinned in place in C#; C# is a garbage-collected language.
In short never use unsafe
unless you thoroughly understand everything there is to know about memory management in C#. You are turning off the safety system that is there to protect you, and so you have to know what that safety system does.
The code should be:
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;
}
}
The problem is with the line:
Node* T=new Node();
In C#, new Node()
returns Node
(which is reference), not Node*
(which is pointer).
You should use stackalloc, instead.
Anyway, please do not copy C++ and do it C# way!
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