X hits on this document





337 / 396


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++.

18.5.4 The address-of operator

An addressof-expression consists of an ampersand (&) followed by a unary-expression.

addressof-expression: &   unary-expression

Given an expression E which is of a type T and is classified as a fixed variable (§‎18.3), the construct &E computes the address of the variable given by E. The type of the result is T* and is classified as a value. A compile-time error occurs if E is not classified as a variable, if E is classified as a volatile field (§‎10.4.3), or if E denotes a moveable variable. In the last case, a fixed statement (§‎18.6) can be used to temporarily “fix” the variable before obtaining its address.

The & operator does not require its argument to be definitely assigned, but following an & operation, the variable to which the operator is applied is considered definitely assigned in the execution path in which the operation occurs. It is the responsibility of the programmer to ensure that correct initialization of the variable actually does take place in this situation.

In the example

using System;

class Test { static void Main() { int i; unsafe { int* p = &i; *p = 123; } Console.WriteLine(i); } }

324Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views644
Page views644
Page last viewedThu Oct 27 03:26:27 UTC 2016