Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct Pointer Initialization 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 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)

like image 500
shoayb Avatar asked Dec 31 '11 10:12

shoayb


People also ask

How do you initialize a struct pointer?

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.

What is initialization of pointer in C?

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 .

How are structs initialized in C?

Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.


2 Answers

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;
    }
}
like image 192
Eric Lippert Avatar answered Oct 22 '22 03:10

Eric Lippert


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!

like image 38
Krizz Avatar answered Oct 22 '22 03:10

Krizz