
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1070
|
Chapter 19: Unsafe Code
displays the following:
p2 > p1
(p2 == p1) = False
(p2 != p1) = True
p2 == p1
(p2 == p1) = True
(p2 != p1) = False
Using the >, <, >=,or<= comparison operators, you can determine whether two
pointers are pointing to a higher, a lower, or the same element in an array. For exam-
ple, the code:
unsafe
{
int[] arr = new int[5] {1,2,3,4,5};
fixed(int* ptrArr = &arr[0])
{
int* p1 = (ptrArr + 1);
int* p2 = (ptrArr + 3);
Console.WriteLine("p2 > p1");
Console.WriteLine("(p2 > p1) = " + (p2 > p1));
Console.WriteLine("(p2 < p1) = " + (p2 < p1));
Console.WriteLine("(p2 >= p1) = " + (p2 >= p1));
Console.WriteLine("(p2 <= p1) = " + (p2 <= p1));
p2 = p1;
Console.WriteLine("p2 == p1");
Console.WriteLine("(p2 > p1) = " + (p2 > p1));
Console.WriteLine("(p2 < p1) = " + (p2 < p1));
Console.WriteLine("(p2 >= p1) = " + (p2 >= p1));
Console.WriteLine("(p2 <= p1) = " + (p2 <= p1));
}
}
displays the following:
p2 > p1
(p2 > p1) = True
(p2 < p1) = False
(p2 >= p1) = True
(p2 <= p1) = False
p2 == p1
(p2 > p1) = False
(p2 < p1) = False
(p2 >= p1) = True
(p2 <= p1) = True
Discussion
When manipulating the addresses that pointers point to, it is sometimes necessary to
compare their addresses. The
==, !=, >, <, >=, and <= operators have been overloaded