How to: Access an Array Element with a Pointer (C# Programming Guide)

In an unsafe context, you can access an element in memory by using pointer element access, as shown in the following example:

       char* charPointer = stackalloc char[123];
      for (int i = 65; i < 123; i++)
      {
          charPointer[i] = (char)i; //access array elements
      }

The expression in square brackets must be implicitly convertible to int, uint, long, or ulong. The operation p[e] is equivalent to *(p+e). Like C and C++, the pointer element access does not check for out-of-bounds errors.

Example

In this example, 123 memory locations are allocated to a character array, charPointer. The array is used to display the lowercase letters and the uppercase letters in two for loops.

Notice that the expression charPointer[i] is equivalent to the expression *(charPointer + i), and you can obtain the same result by using either of the two expressions.

// compile with: /unsafe
class Pointers
{
    unsafe static void Main() 
    {
        char* charPointer = stackalloc char[123];

        for (int i = 65; i < 123; i++)
        {
            charPointer[i] = (char)i;
        }

        // Print uppercase letters:
        System.Console.WriteLine("Uppercase letters:");
        for (int i = 65; i < 91; i++)
        {
            System.Console.Write(charPointer[i]);
        }
        System.Console.WriteLine();

        // Print lowercase letters:
        System.Console.WriteLine("Lowercase letters:");
        for (int i = 97; i < 123; i++)
        {
            System.Console.Write(charPointer[i]);
        }
    }
}
Uppercase letters:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Lowercase letters:
abcdefghijklmnopqrstuvwxyz

See Also

Reference

Pointer Expressions (C# Programming Guide)

Pointer types (C# Programming Guide)

unsafe (C# Reference)

fixed Statement (C# Reference)

stackalloc (C# Reference)

Concepts

C# Programming Guide

Other Resources

Types (C# Reference)