Arithmetic Operations on Pointers

Arithmetic Operations on Pointers (C# Programming Guide)


This topic discusses using the arithmetic operators + and - to manipulate pointers.


You cannot perform any arithmetic operations on void pointers.

You can add a value n of type int, uint, long, or ulong to a pointer, p, of any type except void*. The result p+n is the pointer resulting from adding n * sizeof(p) to the address of p. Similarly, p-n is the pointer resulting from subtracting n * sizeof(p) from the address of p.

You can also subtract pointers of the same type. The result is always of the type long. For example, if p1 and p2 are pointers of the type pointer-type*, then the expression p1-p2 results in:

((long)p1 - (long)p2)/sizeof(pointer_type)

No exceptions are generated when the arithmetic operation overflows the domain of the pointer, and the result depends on the implementation.

// compile with: /unsafe
class PointerArithmetic
    unsafe static void Main() 
        int* memory = stackalloc int[30];
        long difference;
        int* p1 = &memory[4];
        int* p2 = &memory[10];

        difference = p2 - p1;

        System.Console.WriteLine("The difference is: {0}", difference);
// Output:  The difference is: 6

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

© 2015 Microsoft