C# does not like pointers, but I need to use them now to create a linked list, like we would do in C. The struct is simple:
public unsafe struct Livro
{
public string name;
public Livro* next;
}
But I get the error: "Cannot take the address of, get the size of, or declare a pointer to a managed type". Any ideas?
You can just use a class
instead of a struct
:
public class Livro
{
public string Name { get; set; }
public Livro Next { get; set; }
}
This will provide the proper behavior automatically.
That being said, you might want to just use the LinkedList<T>
class from the framework directly.
The problem is the string declaration. You have to go low level and use char* pointers. Using unsafe
comes with all the headaches of leaving the managed world...
Any ideas?
Use a class instead of a struct and then the pointer becomes a reference:
public class Livro
{
public string name;
public Livro next;
}
And then it would be a good idea to use properties instead of public fields.
you can do it with struct like this:
struct LinkedList
{
public int data;
public LinkedListPtr next;
public class LinkedListPtr
{
public LinkedList list;
}
}
or like this:
struct LinkedList
{
public int data;
public LinkedList[] next;
}
but it's better to just use class
for the linked list instead.