Export (0) Print
Expand All

A.5.3 Pointer element access

Visual Studio .NET 2003

A pointer-element-access consists of a primary-no-array-creation-expression followed by an expression enclosed in "[" and "]".

pointer-element-access:
primary-no-array-creation-expression   [   expression   ]

In a pointer element access of the form P[E], P must be an expression of a pointer type other than void*, and E must be an expression of a type that can be implicitly converted to int, uint, long, or ulong.

A pointer element access of the form P[E] is evaluated exactly as *(P + E). For a description of the pointer indirection operator (*), see Section A.5.1. For a description of the pointer addition operator (+), see Section A.5.6.

In the example

class Test
{
   static void Main() {
      unsafe {
         char* p = stackalloc char[256];
         for (int i = 0; i < 256; i++) p[i] = (char)i;
      }
   }
}

a pointer element access is used to initialize the character buffer in a for loop. Because the operation P[E] is precisely equivalent to *(P + E), the example could equally well have been written:

class Test
{
   static void Main() {
      unsafe {
         char* p = stackalloc char[256];
         for (int i = 0; i < 256; i++) *(p + i) = (char)i;
      }
   }
}

The pointer element access operator does not check for out-of-bounds errors and the behavior when accessing an out-of-bounds element is undefined. This is the same as C and C++.

Show:
© 2014 Microsoft