C# Pointers
A pointer is a variable that holds the memory address of another type. In C#, pointers can only be declared to hold the memory addresses of value types (except in the case of arrays).
Pointers are declared implicitly, using the symbol *, as in the following example:
int *p;
[Note that some coders place the dereferencer symbol immediately after the type name, eg.
int* p;
This variation appears to work just as well as the previous one.]
This declaration sets up a pointer 'p', which will point to the initial memory address of an integer (stored in four bytes).
The combined syntactical element *p ('p' prefixed by the dereferencer symbol '*') is used to refer to the type located at the memory location held by p. Hence given its declaration, *p can appear in integer assignments like the following:
*p = 5;
This code gives the value 5 to the integer that was initialised by the declaration. It is important, however, not to confuse such an assignment with one in which the derefencer symbol is absent, e.g.
p = 5;
The effect of this assignment is to change the memory location held by p. It doesn't change the value of the integer initialised by the original declaration; it just means that p no longer points to that integer. In fact, p will now point to the start of the four bytes present at memory location 5.
Another important symbol for using pointers is the operator &, which in this context returns the memory address of the variable it prefixes. To give an example of this symbol, the following code sets up p to point to integer i's memory location:
int i = 5;
int *p;
p = &i;
Given the above, the code
*p = 10;
changes the value of i to 10, since '*p' can be read as 'the integer located at the memory value held by p'.
Let us take a look at the following exmple that captures most of the concepts stated above
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int x ; unsafe { int x = 100; /* The &x gives the memory address of the variable x, * which we can assign to a pointer variable */ int* ptr = &x; Console.WriteLine((int)ptr); // Displays the memory address Console.WriteLine(*ptr); // Displays the value at the memory Console.ReadLine(); } } } |
Before you will be able to run the above code you will have to change some settings. Go to Projects -> Properties ->Build and check the checkbox against "Allow unsafe code".
If you run the above code, you should see the output something similar to the below.
69725392 100 |
No comments:
Post a Comment