Pointer is a variable which holds the address of another variable that it points to an address in a memory. The following arithmetic operations are valid to be performed on pointers.
- Assignment Operator(=)
- Increment Operator(++)
- Decrement Operator(–)
- Addition(+)
- Subtraction(-)
- Comparision Operator(==, <, >, !=, <=, >=)
#include <stdio.h>
int main()
{
int myarray[5] = {2, 4,6, 8,10};
int* myptr = NULL;
myptr = myarray;
printf("\n First element in the array :%d", *myptr);
myptr ++;
printf("\n Next element in the array :%d", *myptr);
myptr +=1;
printf("\n Next element in the array :%d", *myptr);
myptr--;
printf("\n Previous element in the array :%d", *myptr);
myptr -= 1;
printf("\n Previous element in the array :%d", *myptr);
return 0;
}
Output:
First element in the array :2
Next element in the array :4
Next element in the array :6
Previous element in the array :4
Previous element in the array :2
Note that the increment operator ++ increments the pointer and points to the next element in the array. Similarly, the decrement operator decrements the pointer variable by 1 so that it points to the previous element in the array.
We also use + and – operators. First, we have added 1 to the pointer variable. The result shows that it points to the next element in the array. Similarly, – operator makes the pointer variable to point to the previous element in the array.
Apart from these arithmetic operators, we can also use comparison operators like ==, < and > but multiplication or division operator cannot be used.
Relevant Posts:
Categories: C Language
Leave a Reply