C tutorial: pointer Arithmetic in C

Programming languages or concepts

pointer Arithmetic in C 


in previous tutorial we are learning what is pointer and how to manipulate pointers. In this tutorial you will be learning the arithmetic operations on pointers.

There are multiple arithmetic operations that can be applied on C pointer: ++,--,-,+  
  Increment.  (++)
  Decrement. ( -- )
  Subtraction ( - )
  Addition.  ( + )


  Incrementing pointer in C:

 we can traverse an array using the increment operations on a pointer which will be keep pointing to every element of the array.
 Mobile for 32 bit int variable it will be incremented by 2 bytes and for 64 bit it will increment 4 bytes.
  if we want to increment a pointer by 1, the pointer will start pointing to the the immediate next location.
Syntax:
new_address = Current_address + 1*sizeof (data type)

#include<studio.h>
int main ( )
{
    int num = 99;
    int *p;
    p =&mark;
     printf("Address of p variable is %u \n",p );
     p = p +1;
     printf("After increment: Address of p variable is%u \n",p);
return 0;
 }

Decrementing pointer in C:

   This operation is like the increment operation, we can increment a pointer variables. If we decrement pointer it will be started pointing to the previous location. for 32 bit in variable, it will be requirement by 2 bytes & 64bits increment by 4 bytes.
Syntax:
new_address = current_address -i *size_of(data type)



C pointer addition:

   We can add value to the pointer variable.
For 32 bit in variable it will add 2 * number & 64 bit in 12 level it will add 4 * number.
Syntax:
new_address = current_address + ( number*size_of(data type))

Ex.

##include<stdio.h>  
int main()
{  

int number=50;        

int *ptr;

ptr=&number;

printf("Address of ptr variable is %u \n",ptr);       
 
ptr=ptr+3;

printf("After adding 3: Address of ptr variable is %u \n",ptr);       

return 0;  

}    

C pointer subtraction

   we can subtract a value from the pointer variables.
Subtracting any numbers from a pointer will given an address.
Force 32 bit incredible it will subtract 2 * number and 64 bit in variable it will subtract 4 * number
  
  1. #include<stdio.h>  
  2. int main(){  
  3. int number=50;        
  4. int *ptr;//pointer
  5. ptr=&number;    
  6. printf("Address of ptr variable is %u \n",ptr);        
  7. ptr = ptr - 3;  
  8. printf("After adding 3: Address of ptr variable is %u \n",ptr);       
  9. return 0;  
  10. }    

close