Professional Documents
Culture Documents
L8 - Pointers
L8 - Pointers
Pointers
1
Tazwar Bakhtiyar Zahid
Lecturer,
Department of Civil Engineering,
BUET
2
Pointers
• The type of the variable that stores an address is
called a pointer
• Pointer variables have the derived type “pointer to
T”, where T is the type of the object to which the
pointer points
• A memory bin has an address and is usually
expressed in hexadecimal
• We can store the address of a memory bin (i.e. of a
variable name) in a pointer
• Then we can access that bin by the pointer as well as
by the variable name 3
Declaring Pointers
• long *pnumber;
• int *pnumber;
6
Address of Operator
#include <iostream>
using namespace std;
int main()
{
int x, y;
int *px;
int *py;
x=10;
px=&x;
py=&y;
y=*px;
cout<<" x ="<<x<<" y ="<<y<<endl;
cout<<"\n *px ="<<*px<<" *py ="<<*py<<endl;
} 7
Address of Operator
8
Initializing Pointers
• It is easy to initialize a pointer with the address of a
variable
Output:
&n = 0064fde4, &rn = 0064fde4
&rn2 = 0064fde4, &rn3 = 0064fde4
• N.B.: This output varies from program to program
• The first line of output shows that n and rn have the
same address: 0064fde4
• Thus they are merely different names for the same
object
14
Pointers to Pointers
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n=44;
cout << " n = " << n << endl;
cout << " &n = " << &n << endl;
int* pn=&n; // pn holds the address of n
cout << " pn = " << pn << endl;
cout << " &pn = " << &pn << endl;
cout << " *pn = " << *pn << endl;
int** ppn=&pn; // ppn holds the address of pn
15
Pointers to Pointers
cout << " ppn = " << ppn << endl;
cout << " &ppn = " << &ppn << endl;
cout << " *ppn = " << *ppn << endl;
cout << "**ppn = " << **ppn << endl;
}
Output: n = 44
&n = 0064fd78
pn = 0064fd78
&pn = 0064fd7c
*pn = 44
ppn = 0064fd7c
&ppn = 0064fd80
*ppn = 0064fd78
**ppn = 44 16
Array and Pointers
• The array and a pointer have similarity in that both
contain an address
• double value[5];
19
Array and Pointers
• We can also use the name of an array as though it
was a pointer
20
Array and Pointers
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double value[10][10];
int m,n;
cout<<" No. of rows (max 10)? ";
cin>>m;
cout<<" No. of columns (max 10)? ";
cin>>n;
cout<<" Input the elements of the matrix
(row wise)\n ";
int i,j; 21
Array and Pointers
for(i=0; i<m; i++)
{for(j=0; j<n; j++)cin>>value[i][j];}
for(i=0; i<m; i++)
{for(j=0; j<n; j++)cout<<setw(7)<<value[i][j];
cout<<endl;}
cout<<"value[1][2] = "<<value[1][2]<<endl;
cout<<"*(*(value+1)+2)="<<*(*(value+1)+2)
<<endl;
}
22
Dynamic Memory Allocation
• When we declare a variable or an array in the source
code in the form
int salary;
string address;
double ce204[50];
24
Dynamic Memory Allocation
• This unused memory is called free store or heap
double *pvalue;