次の方法で共有


Accessing an Element via Pointer (C# Programming Guide) 

You can access an element in memory with a pointer element access, which takes the form:

primary-no-array-creation expression [expression]

Parameters

  • primary-no-array-creation expression
    A pointer type expression other than void*.
  • expression
    An expression that can be implicitly converted to int, uint, long, or ulong.

Remarks

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.

Note

Notice that the expression charPointer[i] is equivalent to the expression *(charPointer + i), and you can obtain the same result by using either one 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]);
        }
    }
}

Output

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)