Pointer Arithmetic and Arrays
Subscript operator is used to access an element of an array which implements an address arithmetic, like a pointer.
Pointer comparisons
Pointers may be compared by using relational operators, such as ==, < and >.
If p1 and p2 point to a variable that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared.
#include<stdio.h>
const int MAX=3;
int main()
{
/* Declaration and initializing an int array with 3 elements */
int var[] = {10,100,200};
int i, *ptr;
ptr=&var[MAX-1]; //Pointer now points to arrary i.e. last element
for(i=MAX; i>0; i--)
{
printf(“Address of var[%d]=%x\n”, i,ptr); //Address of the current element
printf(“Value of var[%d]=%d\n”,i, *ptr); //Content of the current element
ptr--; //move to the previous location //The – operator works the same way in normal variables and pointer variables. The pointer now points to one address before.
}
return();
}
OUTPUT
Address of var[3] = fff4
Value of Var[3]=200
Address of var[2] = fff2
Value of var[2] = 100
Address of var[1] = fff0
Value of var[1] = 10
Explanation:
The 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]: