Question

New to pointers and unsafe world in C#. I was going through getting memory address of variables via pointers, move things around a bit here and there etc; basically learning.

static unsafe void M()
{
    var i = 1;
    var p = &i; //gets memory location of variable i here

    //how do I write to location p, say a value of 100?
}

I was wondering if there is a way to write to a specific location as well? It helps a great deal to see what's going around if I can read and write at the same time.

No practical purposes, just learning. Or is it not possible with C#?

Was it helpful?

Solution

You need to dereference the pointer with the * operator. ex:

*p = 100;

OTHER TIPS

Like this

*p = 100;

Console.WriteLine(i); // prints 100;

You need to deference it.

Here's a LINQPad snippet:

int i = 1;

unsafe
{
    var p = &i;

    *p = 100;
}

i.Dump();

This outputs "100", as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top