Beruflich Dokumente
Kultur Dokumente
Page 1
Introduction
• A pointer in C is an address, which is a
numeric value.
Therefore , we can perform arithmetic operations
on a pointer.
Page 2
Concept
Page 3
Simple Example of Pointer Arithmetic
int *i;
i++ ;
Page 4
Simple Example of Pointer
Arithmetic
float *i;
i++ ;
Page 5
POINTER ARITHMETIC OPERATIONS
1. Incrementing pointer
2. Decrementing a pointer
3. Addition of Pointer and a number
4. Subtraction of Pointer and a number
5. Differencing between two Pointers
6. Comparison between two Pointers
Page 6
1. Incrementing pointer
Page 7
1. Incrementing pointer
Page 8
1. Incrementing pointer
main()
{
int *ptr = (int *) 1000 ;
ptr++; //ptr = ptr + 1 ;
printf(“ new value of ptr : %d”, ptr);
}
OUTPUT:
New value of ptr : 1002
Page 9
2. Decrementing pointer
Page 10
2. Decrementing pointer
main()
{
int *ptr = (int *) 1000 ;
ptr-- ; //ptr = ptr - 1 ;
printf(“ new value of ptr : %d”, ptr);
}
OUTPUT:
New value of ptr : 998
Page 11
3. Addition of Pointer and a number
main()
{
int *ptr = (int *)1000;
ptr = ptr + 3;
printf(“ new value of ptr : %d”, ptr);
}
OUTPUT:
New value of ptr : 1006
Page 12
4. Subtraction of Pointer and a number
main()
{
int *ptr = (int *)1000;
ptr = ptr - 3;
printf(“ new value of ptr : %d”, ptr);
}
OUTPUT:
New value of ptr : 994
Page 13
5. Differencing between two Pointers
Page 14
5. Differencing between two Pointers
main()
{
float *ptr1 = (float *)1000;
float *ptr2 = (float *)2000;
printf(“ Difference : %d”, ptr2 – ptr1);
}
OUTPUT:
Difference : 250
Page 15
6. Comparison between two Pointers
• Pointer comparison is valid only if the two
pointers are pointing to same array.
• All relational operators can be used for
comparing pointers of same type/different
type.
• All equality and inequality operators can
be used with all pointer types.
• Pointers cannot be multiplied or divided.
Page 16
EXAMPLE
#include<stdio.h>
int main()
{
int *ptr1,*ptr2;
ptr1 = (int *)1000;
ptr2 = (int *)2000;
if(ptr2 > ptr1)
printf("Ptr2 is far from ptr1");
return(0);
}
Page 17
Page 18