Programming For Engineers Lecture 09
Programming For Engineers Lecture 09
2
Pointers
Pointers
Location
x
60000 10
Address of x
Declaring Pointer to Integer
int *myptr ;
double *x ;
char *c ;
Example
int *ptr ;
int x ;
x = 10 ;
ptr = &x ;
Dereferencing Operator *
*ptr is read as
“The value of what ever ptr points to”
z = *ptr * 2 ;
Initializing Pointers
ptr = &var ;
ptr = 0 ;
ptr = NULL ;
int *ptr , x ;
Declaring pointers
int *ptr , x , a [ 10 ] ;
Bubble Sort
5 1 1 1
1 5 3 2
3 3 5 3
6
6 6 4
2
9 2 5
9
2 4 6
4
4 8 8
8
8 9 9
Swapping
Swap
temp = x ;
x=y;
y = temp ;
Example
main ( )
{
int x = 10 , y = 20 , * yptr , * xptr ;
yptr = &y ;
xptr = &x ;
swap ( yptr , xptr ) ;
}
Example
swap ( int *yptr , int *xptr )
{
………
}
const
int *const myptr = &x ;
is same as
yptr = &y [ 0 ] ;
……..
yptr = &y [ 2 ] ;
Example 2
#include<iostream.h>
main ( )
{
int y [ 10 ] ;
int *yptr ;
yptr = y ;
cout << yptr ;
yptr ++ ;
cout << *yptr ;
}
Example 3
main ( )
{
int x = 10 ;
int *yptr ;
yptr = &x ;
cout << yptr ;
cout << *yptr ;
*yptr ++ ;
increment whatever yptr points to
}
Pointer Arithmetic
*yptr + 3 ; This Is an Expression
yptr = &x ;
yptr ++ ;
Pointer Arithmetic
int x =10 ;
int *yptr ;
yptr = &x ;
*yptr += 3 ;
yptr += 3 ;
Decrementing
*yptr --
Pointer Arithmetic
int *p1 ,*p2;
…..
p1 + p2 ;
Error
Pointer Arithmetic
int y [ 10 ] , *y1 , *y2 ;
y1 = &y [ 0 ] ;
y2 = &y [ 3 ] ;
cout << y2 - y1 ;
Pointer Arithmetic
int y [ 10 ] ;
int *yptr ;
yptr = y [ 5 ] ;
cout << *( yptr + 5 ) ;
Pointer Comparison
if ( y1 > y2 )
if ( y1 >= y2 )
if ( y1 == y2 )
Pointer Comparison