C# pointer Operations

This Tutorial Has Been Viewed 555 Times.

Pointer Notation

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 – see below).

Pointers are declared implicitly, using the ‘dereferencer’ 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’.

There is another important piece of notation for pointers. Pointers can be declared for structs , as in the following example (which uses the ‘Coords’ struct defined further below):

Coords x = new Coords();
Coords *y = &x;

One can then use the declared pointer y to access a public field of x (say z). This would be done using either the expression

(*y).z

or the equivalent expression, which uses the -> string:

y -> z

VN:F [1.9.13_1145]
Rating: 4.0/10 (1 vote cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

C# pointer Operations, 4.0 out of 10 based on 1 rating

Incoming search terms:

Tags:

Leave a Reply

Spam protection by WP Captcha-Free

Proudly designed by Mistonline.in.
Affordable Seo PackagesSeo BlogEdu Backlinks
More in C# (4 of 5 articles)