We have seen pointers in different expressions and arithmetic operations. Can we compare pointers? Yes, two pointers can be compared. Pointers can be used in conditional statements as usual variables. All the comparison operators can be used with pointers i.e. less than, greater than, equal to, etc. Suppose in sorting an array we are usingtwo pointers. To test which pointer is at higher address, we can compare them and take decision depending on the result.
Again consider the two pointers to integer i.e. yptr1 and yptr2. Can we compare *yptr1 and *yptr2? Obviously *yptr1 and *yptr2 are simple values. It is the value of integer yptr1, yptr2 points to. When we say *yptr1 > *yptr2, this is a comparison of simple two integer values. Whenever we are using the dereference pointer (pointers with *), all normal arithmetic and manipulation is valid. Whenever we are using pointers themselves, then certain type of operations are allowed and restrictions on other.Consider a sample program as follows:
/* Program using the dereference
pointer comparison */
The output of the program is;
More on Pointer Arithmetic
Pointers are associated to some data type as pointer to integer, pointer to float and pointer to char etc. When a pointer is incremented or decremented, it changes the address by the number of bytes occupied by the data type that the pointer points to.
For example, if we have a pointer to an integer, by incrementing the
pointer the address will be incremented by four bytes, provided the integer
occupies four bytes on that machine. If it is a pointer to float and float
occupies eight bytes, then by incrementing this pointer, its address will
be incremented by eight bytes. Similarly, in case of a pointer to a char,
which normally takes one byte, incrementing a pointer to char will change
the address by one.We have seen that we can do different arithmetic operations
with pointers. Let's see can two pointers be added? Suppose we have two
pointers yptr1 and yptr2 to integer and
yptr1 + yptr2 ;
The compiler will show an error in this statement. Think logically what we can obtain by adding the two memory addresses. Therefore, normally compiler will not allow this operation. Can we subtract the pointers? Yes, we can. Suppose we have two pointers pointing to the same memory address. When we subtract these, the answer will be zero. Similarly, if a pointer is pointing to the first element of an integer array while another pointer pointing to the second element of the array. We can subtract the first pointer from second one. Here the answer will be one, i.e. how many array elements are these two pointers apart.