X hits on this document

1071 views

0 shares

342 / 396

Chapter ‎18   Unsafe code

The third and fourth fixed statements in the example above produce identical results. In general, for an array 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); } } }

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 are stored such that the indices of the rightmost dimension are increased first, then the next left dimension, and so on to the left. Within a fixed statement that obtains a pointer p to an array instance a, the pointer values ranging from p to p + a.Length - 1 represent addresses of the elements in the array. Likewise, the variables ranging from p[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.

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 linear p[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: