ADDRESS ARITHMETIC:
1. The only possible operation on two pointer variables is subtraction.
No other operation is possible. Whenever a subtraction operation is performed
on two pointer variable, it gives the number of values that can be stored
between those two addresses.
Eg.,
int *p1,*p2;
Suppose p1=5000, p2=5040
Then, p2-p1=(5040-5000)= 40/2 =20.
i.e., 20 integer values can be stored between
these two addresses.
Eg.,
float *p1,*p2;
Suppose p1=5000, p2=5040
Then, p2-p1=(5040-5000) = 40/4 =10.
i.e., 10 floating point values can be stored
between these two addresses.
Eg.,
char *p1,*p2;
Suppose p1=5000,p2=5040
Then, p2-p1=(5040-5000)=40/1=40.
i.e., 40 character values can be stored
between these two addresses.
2. Increment/decrement operations can be performed on pointer variables.
Eg.,
int *p1;
Let p1=5000
p1++; or ++p1;
The incrementation operation causes the pointer variable increments to
length of the datatype which is known as scaling factor.
Hence, p1++ or ++p1 causes it
to point to 5002. Since p1 is an integer pointer, an integer occupies 2 bytes,
it increments by two locations.
Similarly the decrement operation causes the
variable to point to the address after subtracting the scaling factor.
Eg.,
float *p1;
Let p1=5000
p1- -; or - -p1;
After the decrement operation,
p1 points to 4996.Since here the scaling factor is 4. Likewise, the scaling
factor for character is 1.
3. When we add any integer value to the pointer variable, the integer
vlue gets multiplied with the scaling factor and corresponding number of bytes
will be added.
Eg.,
int *p1;
Suppose p1=5000
P1+10=5000+10
=5000+(10*2)
=5020
Similarly, subtraction operation
will be as follows:
Eg.,
float *p1;
Suppose p1=5000
P1-10=5000-10
=5000-(10*4)
=4960.
Ø A
Program for increment operation on pointers.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=5,*p1;
p1=&a;
float b=15.5,*p2;
p2=&b;
char c=’a’,*p3;
p3=&c;
printf(“addresses are %u,%u,%u”,p1,p2,p3);
printf(“after incrementation\n”);
p1++;
p2++;
p3++;
printf(“addresses are %u,%u,%u”,p1,p2,p3);
getch( );
}
No comments:
Post a Comment