3

I have a trouble creating managed array of pointers.

I've tried

public unsafe class Car
{
    public int speed;

    public Car()
    {
        speed = 0;
    }

    public Car(int speed)
    {
        this.speed = speed;
    }
}

class Program
{
    public static unsafe void Main(string[] args)
    {
        var arr = new Car[10]; // 1st way
        fixed(Car* ptr = arr)
        {}

        Car* arr = stackalloc Car[10]; // 2nd way
    }
}

After both tries I get the same error: "Impossible to get adress or size or define a pointer of managed type". Does somebody know how to fix it?

4
  • 1
    What are you trying to achieve, and why do you think pointers are the way to solve your problem? Commented Sep 15, 2019 at 17:04
  • This is a task from a lab in the university, There is a class Car and I need to create array of 10 pointers. Commented Sep 15, 2019 at 19:33
  • You've been specifically asked to use pointers? Commented Sep 15, 2019 at 20:18
  • Yes, there are a few tasks in a row. Write a definition of a function which returns long and gets int. Change this task as if the func was a member of a class Car. Define array of 10 pointers of class Car. Commented Sep 16, 2019 at 9:55

1 Answer 1

1

Well, as C# specs say:

Unlike references (values of reference types), pointers are not tracked by the garbage collector—the garbage collector has no knowledge of pointers and the data to which they point.

For this reason a pointer is not permitted to point to a reference or to a struct that contains references, and the referent type of a pointer must be an unmanaged-type. An unmanaged-type is any type that isn’t a reference-type and doesn’t contain reference-type fields at any level of nesting. In other words, an unmanaged-type is one of the following:

sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.

Any enum-type.

Any pointer-type. Any user-defined struct-type that contains fields of unmanaged-types only.

Sign up to request clarification or add additional context in comments.

1 Comment

I got it, so I can't define a pointer of managed class? There's no way to fix it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.