Pointer usage in C#, it must be in unsafe context
static unsafe void Main()
{
int i;
int[] array = { 11, 22, 33 };
// pointer pi has the address of variable i
int* pi = & i;
// ppi(addess of pi) < pi(addess of i) < i(0)
i = 0;
// dereference the pi, i.e. *pi is i
Console.WriteLine("i = {0}", *pi); // output: i = 0
// since *pi is i, equivalent to i++
(*pi)++;
Console.WriteLine("i = {0}", *pi); // output: i = 1
// pointer to a pointer, pointer ppi has the address
// of variable pi
int** ppi = π
// since *ppi is pi, one more dereference *pi is i
// equivalent to i += 2
* *ppi += 2;
Console.WriteLine("i = {0}", *pi);// output: i = 3
// pointer to an array
fixed (int* parray = array)
{
// get a copy of parray in fixed context.
int* p = parray;
Console.WriteLine(*(p++));// output: 11
Console.WriteLine(*(p++));// output: 22
Console.WriteLine(*(p++));// output: 33
}
Console.ReadLine();
}
Tags: C#, Pointer, unsafe
Leave a Reply