PointersT c++
PointersT c++
• Initialization of pointer
datatype *varable_name=& other variable // referencing
• Example :
int *x = &y ;
int* x = &y ;
int * x = & y ;
Declaration and Initialization pointer
point to another pointer
Pointer : can be used to point to another
pointer also i.e it can store the address of
another pointer.
Differences between & and *
& is the reference operator and can be read
as "address of“.
* is the dereference operator and can be
read as "value pointed by“
All expressions below are true:
• x= 25;
• y = &x;
• x == 25 // true
• &x == 1776 // true
• y == 1776 // true
• *y == 25 // true
Examples
#include <iostream.h>
int main ()
{
int var1;
char var2;
cout << "Address of var1 variable: ";
cout << &var1 << endl;
cout << "Address of var2 variable: ";
cout << &var2 << endl;
return 0; Output
} Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6
Examples
#include <iostream.h>
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0; Output
} Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Examples
#include<iosream.h>
int main()
{
int a=100;
int *p1;
int * *p2;
p1=&a; //p1 points to address of a
p2=&p1; // p2 points to address of p1
cout<<“address of a”<<&a;
cout<<“address of a”<<p1;
cout<<“value of a”<< *p1;
cout<<“value of a”<< * *p2;
cout<<p2;
cout<< *p2;
}
Reference variable in C++
When a variable is declared as reference, it becomes an
alternative name
for an existing variable.
A variable can be declared as reference by
putting „&‟ in the declaration.
Program using reference variable
#include<iostream.h> Output
#include<iostream.h>
void add(int,int);
int main()
{
int a,b;
cout<<“enter values of a and b”<<endl;
cin>>a>>b;
add(a,b);
return 0;
}
void add(int x,int y)
{
int c;
c=x+y;
cout<<“addition is”<<c;
}
Call by reference
In function call
We write reference
variable for formal
arguments
add(a,b);
}
void add(int &x,int &y);
{
--------;
} &X,&Y will be the
No need for reference variable for
return a and b. if we change
statement X and Y,Value of a
and b are changed
accordingly.3
Program to illustrate call by reference
#include<iostream.h>
#include<conio.h> void swap(int &X,&Y)
void swap(int &,int &); {
int main() int temp;
{ temp=X;
int a,b;
cout<<“enter the values of a and b”; X=Y;
cin>>a>>b; Y=X;
cout<<“before swaping”; }
cout<<“A”<<a;
cout<<“B”<<b;
swap(a,b);
cout<<“after swaping”;
cout<<“A”<<a;
cout<<“B”<<b; }
Array and pointers