# Understand pointer arithmetic in C in easy way – 3

## Pointer arithmetic in C programming

Let’s suppose we created a pointer *ptr is pointing towards an int variable x which address is 2000. Which means ptr = 2000 because it is storing the address of int variable x.
Now if we shift pointer forward then pointer will start pointing 2004 because from 2000 to 2003, 4 bytes are used to store the value of int variable x.
Hence pointer will not point from 2001 to 2003 memory locations in this scenario, it will shift to 2004 memory location.

Same goes with char and others.
Now the question arises “Which operators are used to increment and decrement pointers?”
There are few arithmetic operators like ++, ——, – and + which can be use to shift pointers forward and backward.
We can also use comparison operators with pointers.

## Increment a pointer

We can shift pointer forward using two operators those are ++, += and + operators.

In below example we can also use ptr+=1 or ptr = ptr + 1 instade of ptr++.

Both will give same output.

`#include <stdio.h>int main (){    int i,nums[]={1,2,3,4,5};    int *ptr = nums;     for(i = 0; i < 5; i++)    {        printf("n nums[%d] = %d -> value : %d",i,ptr,*ptr);        ptr++;    }    return 0;}`

Output :

nums = 6422292 -> value : 1
nums = 6422296 -> value : 2
nums = 6422300 -> value : 3
nums = 6422304 -> value : 4
nums = 6422308 -> value : 5

## Decrement a pointer

We can shift pointer backward using two operators those are ——, -= and operators.

In below example we can also use ptr-=1 or ptr = ptr – 1 instade of ptr——.

Both will give same output.

`#include <stdio.h>int main (){    int i,nums[]={1,2,3,4,5};    int *ptr = &nums;     for(i = 4; i >= 0; i--)    {        printf("n nums[%d] = %d -> value : %d",i,ptr,*ptr);        ptr--;    }return 0;}`

Output :

nums = 6422308 -> value : 5
nums = 6422304 -> value : 4
nums = 6422300 -> value : 3
nums = 6422296 -> value : 2
nums = 6422292 -> value : 1

## Comparison operator with pointer

We can also use comparison operators to compare value pointer with other variable’s address or with value of another pointer.

`#include <stdio.h>int main (){    int i=0,nums[]={1,2,3,4,5};    int *ptr = nums;     while(ptr < &nums)    {        printf("n nums[%d] = %d -> value : %d",nums[i],ptr,*ptr);        ptr++;        i++;    }    return 0;}`

Output :

nums = 6422292 -> value : 1
nums = 6422296 -> value : 2
nums = 6422300 -> value : 3
nums = 6422304 -> value : 4
nums = 6422308 -> value : 5

### Connect with us on following platforms

We are aiming to explain all concepts of C in easiest terms as possible. ITVoyagers
Author