13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>C#</strong> LANGUAGE SPECIFICATIONThe third and fourth fixed statements in the example above produce identical results. In general, for anarray instance a, specifying &a[0] in a fixed statement is the same as simply specifying a.Here’s another example of the fixed statement, this time using string:class Test{static string name = "xx";}unsafe static void F(char* p) {for (int i = 0; p[i] != '\0'; ++i)Console.WriteLine(p[i]);}static void Main() {unsafe {fixed (char* p = name) F(p);fixed (char* p = "xx") F(p);}}end example]In an unsafe context array elements of single-dimensional arrays are stored in increasing index order,starting with index 0 and ending with index Length – 1. For multi-dimensional arrays, array elements arestored such that the indices of the rightmost dimension are increased first, then the next left dimension, andso on to the left.Within a fixed statement that obtains a pointer p to an array instance a, the pointer values ranging from pto p + a.Length - 1 represent addresses of the elements in the array. Likewise, the variables ranging fromp[0] to p[a.Length - 1] represent the actual array elements. Given the way in which arrays are stored ,we can treat an array of any dimension as though it were linear. [Example: For example.using System;class Test{static void Main() {int[,,] a = new int[2,3,4];unsafe {fixed (int* p = a) {for (int i = 0; i < a.Length; ++i) // treat as linearp[i] = i;}}}}for (int i = 0; i < 2; ++i)for (int j = 0; j < 3; ++j) {for (int k = 0; k < 4; ++k)Console.Write("[{0},{1},{2}] = {3,2} ", i, j, k,a[i,j,k]);Console.WriteLine();}which produces the output:[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] = 23end example][Example: In the example330

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!