Reputation: 73193
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#?
Upvotes: 2
Views: 3026
Reputation: 38800
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.
Upvotes: 1
Reputation: 116411
Like this
*p = 100;
Console.WriteLine(i); // prints 100;
Upvotes: 1
Reputation:
You need to dereference the pointer with the *
operator. ex:
*p = 100;
Upvotes: 1