X hits on this document

1014 views

0 shares

0 downloads

0 comments

343 / 396

C# LANGUAGE SPECIFICATION

[0,0,0] =  0 [0,0,1] =  1 [0,0,2] =  2 [0,0,3] =  3 [0,1,0] =  4 [0,1,1] =  5 [0,1,2] =  6 [0,1,3] =  7 [0,2,0] =  8 [0,2,1] =  9 [0,2,2] = 10 [0,2,3] = 11 [1,0,0] = 12 [1,0,1] = 13 [1,0,2] = 14 [1,0,3] = 15 [1,1,0] = 16 [1,1,1] = 17 [1,1,2] = 18 [1,1,3] = 19 [1,2,0] = 20 [1,2,1] = 21 [1,2,2] = 22 [1,2,3] = 23

In the example

class Test { unsafe static void Fill(int* p, int count, int value) { for (; count != 0; count--) *p++ = value; }

static void Main() { int[] a = new int[100]; unsafe { fixed (int* p = a) Fill(p, 100, -1); } } }

a fixed statement is used to fix an array so its address can be passed to a method that takes a pointer.

A char* value produced by fixing a string instance always points to a null-terminated string. Within a fixed statement that obtains a pointer p to a string instance s, the pointer values ranging from p to p + s.Length - 1 represent addresses of the characters in the string, and the pointer value p + s.Length always points to a null character (the character with value '\0').

Modifying objects of managed type through fixed pointers can results in undefined behavior. For example, because strings are immutable, it is the programmer’s responsibility to ensure that the characters referenced by a pointer to a fixed string are not modified.

The automatic null-termination of strings is particularly convenient when calling external APIs that expect “C-style” strings. Note, however, that a string instance is permitted to contain null characters. If such null characters are present, the string will appear truncated when treated as a null-terminated char*.

18.7 Stack allocation

In an unsafe context, a local variable declaration (§‎8.5.1) may include a stack allocation initializer which allocates memory from the call stack.

local-variable-initializer: expression array-initializer stackalloc-initializer

stackalloc-initializer: stackalloc   unmanaged-type   [   expression   ]

The unmanaged-type indicates the type of the items that will be stored in the newly allocated location, and the expression indicates the number of these items. Taken together, these specify the required allocation size. Since the size of a stack allocation cannot be negative, it is a compile-time error to specify the number of items as a constant-expression that evaluates to a negative value.

A stack allocation initializer of the form stackalloc T[E] requires T to be an unmanaged type (§‎18.2) and E to be an expression of type int. The construct allocates E * sizeof(T) bytes from the call stack and returns a pointer, of type T*, to the newly allocated block. If E is a negative value, then the behavior is undefined. If E is zero,

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

Document info
Document views1014
Page views1014
Page last viewedFri Dec 09 17:45:12 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments