
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Navigating Arrays
|
1071
to operate on pointer-type variables. These comparison operators do not compare
the value pointed to by the pointers; instead, they compare the addresses pointed to
by the pointers.
To compare the values pointed to by two pointers: dereference the pointers and then
use a comparison operator on them. For example:
*intPtr == *intPtr2
will compare the values pointed to by these pointers, rather than their addresses.
See Also
See the “C# Operators,” “== Operator,” and “!= Operator” topics in the MSDN
documentation.
19.3 Navigating Arrays
Problem
You need to iterate through the elements of a single-dimensional, multidimensional,
or jagged array using a pointer to that array.
Solution
To enable iteration, create an unsafe pointer that points to an array. The manipula-
tion of the array can then be performed through this pointer.
To create a pointer to a single-dimensional array, declare and initialize the array:
int[] intArray = new int[5] {1, 2, 3, 4, 5};
and then set a pointer, arrayPtr, to the address of the first element in this array (you
must use the
fixed keyword to pin the array in the managed heap so that the gar-
bage collector does not move it):
fixed(int* arrayPtr = &intArray[0])
Note that this line could also be written as:
fixed(int* arrayPtr = intArray)
without