C Pointer arithmetic


In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable.Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable.

Syntax

ptr++;

Example

#include <stdio.h>          
void main(){          
int num = 10;      

//pointer to int
int *p;   

//stores the address of number variable  
p=&num;     
          
printf("Address of p variable is %u \n",p);      
p=p+1;     
printf("After increment: Address of p variable is %u \n",p);      
}    
Output
Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer

To decrementing a pointer, which decreases its value by the number of bytes of its data type.

Syntax

ptr--;

Example

#include <stdio.h>

const int num = 3;

int main ()
{
   int  var[] = {10, 100, 200};
   int  i, *ptr;

   /* let us have array address in pointer */
   ptr = &var[num-1];
   for ( i = num; i > 0; i--)
   {

      printf("Address of var[%d] = %x\n", i, ptr );
      printf("Value of var[%d] = %d\n", i, *ptr );

      /* move to the previous location */
      ptr--;
   }
   return 0;
}
Output
Address of var[3] = bfedbcd8
Value of var[3] = 200
Address of var[2] = bfedbcd4
Value of var[2] = 100
Address of var[1] = bfedbcd0
Value of var[1] = 10

Pointer Addition

Add a value to the pointer variable.

new_address= current_address + (number * size_of(data type))  

Example

#include <stdio.h>          
void main(){          
int num = 50;      

//pointer to int   
int *p; 

//stores the address of number variable 
p = &num;     
          
printf("Address of p variable is %u \n",p);      

//adding 3 to pointer variable  
p = p+3;  
printf("After adding 3: Address of p variable is %u \n",p);      
}    
Output
Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

Pointer Subtraction

Subtract a value from the pointer variable.

Syntax
new_address= current_address - (number * size_of(data type))  

Example

#include <stdio.h>          
void main(){          
int num=50;

//pointer to int     
int *p;   

//stores the address of number variable  
p = &num;     
          
printf("Address of p variable is %u \n",p);      

//subtracting 3 from pointer variable
p = p-3;   
printf("After subtracting 3: Address of p variable is %u \n",p);      
}    
Output
Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

Share this article on