Friday, 30 March 2012

Pointer Arithmetic


Pointer Arithmetic

Pointer variables can also be used in arithmetic expression like adding and subtracting integer variable and manipulation from a pointer variable through the resulting expression.

Different operations perform on pointer are as under:

1. Pointers can be incremented or decremented to point to different location.
    Ex,
            int x=20;
            int *ptr=&x;
            ptr++
            ptr—

here, ptr is a pointer to integer with address of variable x , if ptr has value 65526 then after the operation ptr++ (ptr=ptr+1) , the value of ptr would be 65528.  Increment and decrement in pointer value is based upon the size of data type that it points to.

2.if ptr1 and ptr2 are properly declared and initialized pointers the following operations  are valid
  Ex,
           ans=ans+ *ptr1;
           *ptr1 = *ptr2 +5;
            multi= *ptr1 * *ptr2; 
3. When two pointers point to the same datatype , they can be compared using relational operators
  Ex,
          ptr1==ptr2
          ptr1<ptr2

These comparisons are common in handling arrays.

4. A pointer variable can be assigned the value of another  variable.
    Ex, ptr1=&x;
5. A pointer variable can be assigned the value of another  pointer variable.
    Ex, ptr1=ptr2;

   Here both the pointer points to the object of same data type.
6. A pointer variable can be assigned with NULL or zero value.
   Ex,
          ptr=null;



7. Two pointer variable can not be added
Ex,
          ptr1=ptr1+ptr2;

1.     A pointer variable can not be multiplied or divided with a constant.
Ex,
          ptr1/5
        
2.     A value can not be assigned to an arbitrary address
Ex,
    &ptr=100;
       
   Example:
#include<stdio.h>
#include<conio.h>

void main()
{
int *ptr1,*ptr2;
int a,b,x,y,z;

clrscr();

a=30;b=6;

ptr1=&a;
ptr2=&b;

x=*ptr1+ *ptr2-6;
y=(6 * *ptr1) / (*ptr2 +30);

printf("\n a-> value = %d Address = %u",x,ptr1);
printf("\n b-> value = %d Address = %u",y,ptr2);

printf("\n x= %d  y=%d",x,y);

*ptr1= *ptr1 + 70;
*ptr2= *ptr1;

printf("\n a=%d, b=%d",a,b);

getch();
}

Posted By : Ruchita Pandya

No comments:

Post a Comment