Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

16.2. Comparing Pointers

Problem

You need to know whether two pointers point to the same memory location. If they don’t, you need to know which of the two pointers points to a higher or lower element in the same block of memory.

Solution

Using the == and != operators, we can determine if two pointers point to the same memory location. For example, 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));

        p2 = p1;
        Console.WriteLine("p2 == p1");
        Console.WriteLine("(p2 == p1) = " + (p2 == p1));
        Console.WriteLine("(p2 != p1) = " + (p2 != p1));
    }
}

displays the following:

p2 > p1
(p2 == p1) = False
(p2 != p1) = True

p2 == p1
(p2 == p1) = True
(p2 != p1) = False

Using the >, <, >=, or <= comparison operators, we can determine whether two pointers are pointing to a higher, lower, or the same element in an array. For example, 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata