Thread: Comparing pointers

  1. #1
    Banned
    Join Date
    Apr 2015
    Posts
    596

    Comparing pointers

    How can I generally compare pointers? is it like comparing numbers??

  2. #2
    Registered User Ktulu's Avatar
    Join Date
    Oct 2006
    Posts
    107
    You can compare to see if they point at the same location.

    Code:
    int* p1, p2;
    
    if ( p1 == p2 )
    Or you could compare to see if the value at whatever location they point at, equals.
    Code:
    int* p1, p2;
    
    if ( *p1 == *p2 )
    This parameter is reserved

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    If the pointers point to the elements of the same array (or one past the end thereof) or aggregate (typically a struct object), then you can also use the relational operators (<, <=, >, >=) to compare for their relative locations.

    By the way, Ktulu's post #2 has a common typo error with respect to declaring pointers. This:
    Code:
    int* p1, p2;
    declares p1 to be a pointer to int and p2 to be an int, whereas this:
    Code:
    int *p1, *p2;
    declares both p1 and p2 to be of type int.

    To avoid this kind of mistake, I suggest that you declare them separately:
    Code:
    int *p1;
    int *p2;
    or equivalently:
    Code:
    int* p1;
    int* p2;
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Quote Originally Posted by laserlight View Post
    whereas this:
    Code:
    int *p1, *p2;
    declares both p1 and p2 to be of type int.
    should be "of type pointer-to-int."
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Comparing pointers
    By Deadfool in forum C Programming
    Replies: 3
    Last Post: 10-02-2008, 07:36 PM
  2. comparing pointers/strings
    By ayoros in forum C Programming
    Replies: 2
    Last Post: 12-11-2006, 12:28 PM
  3. Comparing
    By pldd4 in forum C++ Programming
    Replies: 7
    Last Post: 10-30-2002, 03:09 PM
  4. Comparing
    By pldd4 in forum C++ Programming
    Replies: 2
    Last Post: 10-22-2002, 05:26 AM
  5. Comparing Strings using Pointers HELP!!
    By frgmstr in forum C++ Programming
    Replies: 5
    Last Post: 11-01-2001, 12:36 PM