Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <,
and >. If p1 and p2 point to variables that are related to each other,
such as elements of the same array, then p1 and p2 can be meaningfully compared.
The following program modifies the previous example one by incrementing the
variable pointer so long as the address to which it points is either less
than or equal to the address of the last element of the array, which is &var[MAX - 1]:
#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the first element in pointer.
ptr = var;
int i = 0;
while ( ptr <= &var[MAX - 1] )
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the previous location
ptr++;
i++;
}
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Address of var[0] = 0xbfce42d0
Value of var[0] = 10
Address of var[1] = 0xbfce42d4
Value of var[1] = 100
Address of var[2] = 0xbfce42d8
Value of var[2] = 200
No comments:
Post a Comment