Incrementing and Decrementing Pointers (C# Programming Guide)
Use the increment and the decrement operators, ++ and --, to change the pointer location by sizeof (pointer-type) for a pointer of type pointer-type*. The increment and decrement expressions take the following form:
++p;
P++;
--p;
p--;
Parameters
- p
The pointer variable.
- ++
The increment operator.
- --
The decrement operator.
Remarks
The increment and decrement operators can be applied to pointers of any type except the type void*
.
The effect of applying the increment operator to a pointer of the type pointer-type is to add sizeof (pointer-type) to the address contained in the pointer variable.
The effect of applying the decrement operator to a pointer of the type pointer-type is to subtract sizeof (pointer-type) from the address contained in the pointer variable.
No exceptions are generated when the operation overflows the domain of the pointer, and the result depends on the implementation.
Example
In this example, you step through an array by incrementing the pointer by the size of int. With each step, you display the address and the content of the array element.
// compile with: /unsafe
class IncrDecr
{
unsafe static void Main()
{
int[] numbers = {0,1,2,3,4};
// Assign the array address to the pointer:
fixed (int* p1 = numbers)
{
// Step through the array elements:
for(int* p2=p1; p2<p1+numbers.Length; p2++)
{
System.Console.WriteLine("Value:{0} @ Address:{1}", *p2, (long)p2);
}
}
}
}
Sample Output
Value:0 @ Address:12860272
Value:1 @ Address:12860276
Value:2 @ Address:12860280
Value:3 @ Address:12860284
Value:4 @ Address:12860288
See Also
Reference
Pointer Expressions (C# Programming Guide)
C# Operators
Manipulating Pointers (C# Programming Guide)
Pointer types (C# Programming Guide)
unsafe (C# Reference)
fixed Statement (C# Reference)
stackalloc (C# Reference)