Share via


Arithmetic Operations on Pointers (C# Programming Guide)

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

Note

You cannot perform any arithmetic operations on void pointers.

Adding and Subtracting Numeric Values to or From 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.

Subtracting Pointers

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.

Example

// 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 = (long*)(p2 - p1);

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

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 18.5.6 Pointer Arithmetic

See Also

Concepts

C# Programming Guide

Reference

Unsafe Code and Pointers (C# Programming Guide)

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)

Other Resources

Types (C# Reference)