Hey, so im having hard time adapting from C++ pointers to C# and i wonder why is this not compiling? Compiler: “Pointers and fixed size buffers may only be used in an unsafe context”.
struct ObstaclePixel
{
public int x;
public int y;
public Color color;
ObstaclePixel* next;
};
Well basically im creating my own List. I need to keep track of both left and right values in an array and so this is a really fast way to do so. This way basically connects an array. Its pretty basic in dynamic programming tbh.
I don’t have any good links for “C# for C++ programmers,” so here’s a brief run-down:
C# has things it calls “references” which work exactly like pointers except have limitations and auto-shortcuts. Anytime you declare a variable of a class type, it’s implicitly a pointer to that class, with implicit dereferencing. Ex: Cat c1 = new Cat(); c1.name=“fluffy”; is really Cat *c1; … c1->name=“fluffy”;. This means you can never create a class-type variable on the stack (since Cat c1; will always give a pointer.)
A funny rule is structs can’t be newed. When you use new myStruct(), it’s actually a fake new that does nothing. You’re just running the constructor. In C#, classes can only use pointers, and structs, ints, strings can never use pointers. Also for fun, you can’t use (*c1)=(*c2) to copy contents of the cats. There’s no star operation in C#, since it’s automatic whenever you try to use a field.
As you found, C# does have real pointers. But the point of using C# is the automatic garbage collection, which only works if you let it reference count, etc… by using “references.” Unsafe context is sort of a way to say it breaks garbage collection (and Unity also can run programs using it.)
For what you’re doing, just make ObstaclePixel be a class. Then ObstaclePixel next; is automatically a pointer to one. But, sure, C# also has something like the STL, with linkedList classes and so on.