Jerry Smith Jerry Smith - 2 months ago 16
C++ Question

Comparison Of Pointers

I want to compare the memory address and pointer value of

p
,
p + 1
,
q
, and
q + 1
.

I want to understand, what the following values actually mean. I can't quite wrap my head around whats going on.

When I run the code:


  • I get an answer of
    00EFF680
    for everytime I compare the adresss
    p
    with another pointer.

  • I get an answer of
    00EFF670
    for everytime I compare the address of
    q
    with another pointer.

  • I get an answer of
    15726208
    when I look at the pointer value of
    p
    .

  • And I get an answer of
    15726212
    When I look at the pointer value of
    p + 1
    .

  • I get an answer of
    15726192
    when I look at the pointer value of
    q

  • And I get an answer of
    15726200
    Wehn I look at the pointer value of
    q + 1
    .






Code

#include <iostream>
#include <string>
using namespace std;
int main()
{
int val = 20;
double valD = 20;
int *p = &val;
double *q;
q = &valD;
cout << "Memory Address" << endl;
cout << p == p + 1;
cout << endl;
cout << q == q + 1;
cout << endl;
cout << p == q;
cout << endl;
cout << q == p;
cout << endl;
cout << p == q + 1;
cout << endl;
cout << q == p + 1;
cout << endl;
cout << "Now Compare Pointer Value" << endl;
cout << (unsigned long)(p) << endl;
cout << (unsigned long) (p + 1) << endl;
cout << (unsigned long)(q) << endl;
cout << (unsigned long) (q + 1) << endl;
cout <<"--------" << endl;
return 0;
}

Answer

There are a few warnings and/or errors.

The first is that overloaded operator << has higher precedence than the comparison operator (on clang++ -Woverloaded-shift-op-parentheses is the flag).

The second is that there is a comparison of distinct pointer types ('int *' and 'double *').

For the former, parentheses must be placed around the comparison to allow for the comparison to take precedence. For the latter, the pointers should be cast to a type that allows for safe comparison (e.g., size_t).

For instance on line 20, the following would work nicely.

cout << ((size_t) p == (size_t) (q + 1));

As for lines 25-28, this is standard pointer arithmetic. See the explanation here.

Comments