In Today’s Lecture
Pointers and Arrays Manipulations
Pointers Expression
Pointers Arithmetic
The & and * Operators
A pointer is a variable which stores the
address of another variable
& is address operator: it gives us the address
of a variable
* (value operator) gives us the value of a
variable at specified address
Example
#include <iostream.h>
int main()
{
int i =10;
cout<<“the value of variable i is”<< i;
cout<<“the memory address of i is”<<&i;
cout<<“the value of variable i using * operator”
<< *(&i);
return 0;
}
Pointers to anything
x some int
int *x;
int **y;
y some *int some int
double *z; z some double
Example
#include<iostream.h>
Int main()
{
Int i= 10;
Int *x = &i;
Int *y;
y= &i; //pointer assignment can also done as
Cout<<“the pointer x is stored at the memory address”<<&x<<endl;
Cout<<<“the pointer x stores the memory address of I :”<<x<<endl;
Cout<<“the value of I accessed through pointer x is :”<<*x<<endl;
// manipulate the value of I using poiter x
*x = *x + 1;
Cout<<*x<<endl;
Return 0;
}
Pointers and Arrays
int y [ 10 ] ; Starting Address of Array Y
Pointers and Arrays
The name of the array is like a
pointer which contain the
address of the first element
Declaration of a Pointer Variable
int y [ 10 ] ;
int *yptr ;
yptr is a pointer to integer
yptr = y ;
int y [ 10 ] ;
int *yptr ;
yptr = y ;
yptr ++ ;
Pointer
Example 1
#include<iostream.h>
main ( )
{
int y [ 10 ] ;
int *yptr = y ;
yptr = y ;
cout << yptr ;
yptr ++ ;
cout << yptr ;
}
yptr = y ;
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 ;
cout << *yptr ;
*yptr += 3 ;
Pointer Arithmetic
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 ;
Example
int y [ 10 ] ;
int *yptr ;
yptr = y ;
cout << y [ 5 ] ;
cout << ( yptr + 5 ) ;
cout << *( yptr + 5 ) ;